
Glossary: Prime Pages: Top 5000: 
The most efficient way to find all of the small primes
(say all those less than 10,000,000) is by using a
sieve such as the
Sieve of Eratosthenes(ca 240 BC):
Make a list of all the integers less than or equal to n (and greater than one). Strike out the multiples of all primes less than or equal to the square root of n, then the numbers that are left are the primes.For example, to find all the primes less than or equal to 30, first list the numbers from 2 to 30. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30The first number 2 is prime, so keep it (we will color it green) and cross out its multiples (we will color them red), so the red numbers are not prime. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30The first number left (still black) is 3, so it is the first odd prime. Keep it and cross out all of its multiples. We know that all multiples less than 9 (i.e. 6) will already have been crossed out, so we can start crossing out at 3^{2}=9. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30Now the first number left (still black) is 5, the second odd prime. So keep it also and cross out all of its multiples (all multiples less than 5^{2}=25 have already been crossed out, and in fact 25 is the only multiple not yet crossed out). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30The next number left, 7, is larger than the square root of 30, so there are no multiples of 7 to cross off that haven't already been crossed off (14 and 28 by 2, and 21 by 3), and therefore the sieve is complete. Therefore all of the numbers left are primes: {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}. Notice we just found these primes without dividing. This algorithm can be written in pseudocode as follows
This method is so fast that there is no reason to store a large list of primes on a computeran efficient implementation can find them faster than a computer can read from a disk. In fact the problem with the algorithm as presented above is not really speed (it uses O(n(log n)log log n) bit operations), but rather space (it is O(n)). So for large n we usually use a segmented sieve. However, both the time and space theoretically can be improved; for example, Pritchard's "linear segmented wheel sieve" uses O(n log n) bit operations and O(sqrt(n)/log log n) space.
See Also: TrialDivision Related pages (outside of this work)
References:
Chris K. Caldwell © 19992014 (all rights reserved)
