Thursday, April 14, 2011

Sieve of Eratosthenes

To find all the prime numbers less than or equal to a given integer n:
1. Create a list of consecutive integers from two to n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p, count up by p and cross out thus found numbers in the list (which will be 2p,
3p, 4p, etc.).
4. Find the first number not yet crossed out after p; let p now equal this number (which is the
next prime).
5. Repeat steps 3 and 4 until p is greater than n.
All the numbers in the list which are not crossed out are prime.

No comments: