Computer programming has its roots firmly grounded in mathematics, with the earliest computers used to calculate results that would take average human days to do by hand. One compelling problem in the field of computer science is discovering prime numbers.
This post will show the most straightforward approach to calculating prime numbers using C# 9.
What Is A Prime Number?
As a refresher for folks, a prime number is a natural number (a non-negative number) greater than one that is not composed of two smaller natural numbers. In school, we may have encountered our first prime numbers of 2, 3, 5, 7, and 11. Schools commonly teach trial division to determine the primality of any given number, in which we divide a number starting from 2 up to the square root of the number in question.
For example, if we were to determine if 100 was prime, we would divide the number from 2 up to 10. We start with lower factors as commonly, smaller numbers are composites of larger numbers. From a programming perspective, this also ensures we don’t need to perform all the calculations to determine that a number is not prime. In a sense, prime numbers will be the most expensive calculation we need to perform.
While the trial division is the most straightforward approach to calculating prime numbers, computer scientists and mathematicians have developed algorithms to discover larger prime numbers. These other approaches value time speed in favor of accuracy. On December 2018, mathematicians found the largest known prime number with 24,862,048 decimal digits using a different approach than trial division. Like all numbers, the possibility for a prime number is infinite.
To read more about Prime Numbers, check out the Wikipedia page.
Calculate A Number’s Primality
Knowing the formula for trial division, we can write a function that takes a number and attempts to divide our value from 2 to Sqrt(value)*.
Using programming constructs like circuit breaking, we can avoid costly calculations by returning when we find a factor that returns a remainder of 0. The resulting remainder means we’ve found a number that neatly divides into our value. In our case, we use the boolean behavior of evaluation to only call CalculatePrime
when our initial value is greater than one and is a natural number.
Let’s look at the complete solution.
Running our top-level statement file, we get the following console output.
Conclusion
Calculating prime numbers is an excellent starting problem for folks looking to get into software development. There are several ways to solve for prime numbers, but trial division is easy to understand and without calculation flaws. That said, we should not use the approach to find undiscovered prime numbers, as it’s inefficient at doing so. Leave those discoveries to the professionals. I hope you enjoyed this post, and please leave a comment below.