The Sieve of Eratosthenes is an algorithm for finding all prime numbers up to some limit n.
Steps:
- Create a boolean array of
n + 1positions to represent the numbers0throughn. - Set positions
0and1tofalse, and the rest totrue. - Start at the first prime number
p = 2. - Mark as
falseall the multiples ofp. - Find the first position greater than
pthat istruein the array. If there is no such position, stop. Otherwise, letpequal this new number (which is the next prime), and repeat from step 4.
When the algorithm terminates, the numbers remaining true in the array are all the primes below n.
The algorithm has a complexity of O(n log(log n)).
