Prime Sieve of Eratosthenes

The Sieve of Eratosthenes is an algorithm for generating a list of all prime numbers up to a given integer N. It does this using $$O(N)$$ space and $$O(N \lg \lg N)$$ time.

The algorithm
The naive idea to find all primes would be: For each $$m$$ such that $$2\le m\le N$$ if $$m$$ is divisible by some number less than itself, then it is not prime, else it is prime.

The sieve of Eratosthenes turns this idea around, making a simple modification &mdash; instead of going to each number and testing whether it is divisible by a smaller number, it goes to each number and declares all its multiples to be not prime.

Thus, in its simplest version, the algorithm would look like this: Start with an array is_prime[$$2..N$$], all initialized to true. For each $$i$$ such that $$2\le i\le N$$, do  For each multiple $$m$$ of $$i$$ such that $$m\le n$$, "cross out $$m$$", i.e, set is_prime[$$m$$] to false

(At the end, the prime numbers less than $$N$$ are precisely those $$p$$ for which  is true.)

Starting with this simple algorithm, we can make several observations to make it very efficient.


 * 1) If $$m$$ is a multiple of $$i$$ and $$i$$ is a multiple of $$p$$, then $$m$$ is also a multiple of $$p$$. Thus, if $$i$$ has already been crossed out when the algorithm reaches it, we need not go crossing out its multiples, because they would have already been crossed out.
 * 2) If a number $$m$$ is not prime, then it has a factor that is $$\le \sqrt m$$. (This is because if $$m=pq$$, then at least one of $$p$$ and $$q$$ must be $$\le \sqrt m$$.) Thus, any number that is ever crossed out will be crossed out first by a number less than or equal to its square root. Putting this another way, we need not cross out multiples $$m$$ of $$i$$ that are less than $$i^2$$, because if $$m<i^2$$ is composite, it would have already been crossed out by some number smaller than $$i$$.
 * 3) By the above, as we will do nothing for $$i$$ such that $$i^2$$ exceeds $$N$$, we can stop when that happens.

With these observations, we can write the following algorithm: Start with an array is_prime[$$2..N$$], all initialized to true. For each $$i$$ such that $$2\le i$$ and $$i^2 \le N$$, do  If isprime[$$i$$] is true, For each multiple $$m$$ of $$i$$ such that $$i^2 \le m\le n$$, "cross out $$m$$" &mdash; set is_prime[$$m$$] to false

This algorithm is usually what is meant when "the sieve of Eratosthenes" is mentioned.

Optimizations

 * There is no need to store even numbers, as there is only one even prime number. (2, of course.)
 * You can use bitmaps to pack the memory.

Implementations
Implementation in C