|
![]() |
Glossary:
Prime Pages:
![]() |
The most efficient way to find all of the small primes
(say all those less than 10,000,000) is by using 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. 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 (25 is the only one 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 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 pseudo-code as follows
This method is so fast that there is no reason to store a large list of primes on a computer--an 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: trial division Related pages (outside of this work)
References:
Chris Caldwell © 1999-2002 (all rights reserved)
|