Yesterday, I reviewed The Music of the Primes: Searching to Solve the Greatest Mystery in Mathematics, a book by Marcus du Sautoy.
In the book, du Sautoy explains the Sieve of Eratosthenes, an algorithm for finding all the prime numbers under a given limit. The concept is surprisingly simple – for a set of numbers less than N, begin with the first prime number (2) and throw out all of its multiples (4, 6, 8, etc) up to N. Then start over with the next number remaining (3) and throw out all of its multiples up to N. Some multiples of 3, such as 6 and 12, will have been thrown out in the prior step. Keep repeating the process until there are no numbers less than N left to be thrown out.
Example where N = 25:
– Bold numbers are the ones being eliminated in each pass.
– The number 1 is not a prime number and is ignored
Start: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
First Pass (multiples of 2): 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25
Second Pass (multiples of 3): 2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25
Third Pass (multiples of 5): 2, 3, 5, 7, 11, 13, 17, 19, 23, 25
Fourth Pass (multiples of 7): 2, 3, 5, 7, 11, 13, 17, 19, 23
There are no multiples of 7 to be thrown out on the fourth pass. Thus, there are 9 prime numbers less than or equal to 25.
Here’s a C# console app I wrote that displays every prime number less than or equal to N using the sieve algorithm.
The Sieve of Eratosthenes
