Prime Sieve of Eratosthenes

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 \log \log n)$$ time.

Algorithm

 * 1) Start off with an array is_prime[2..N], all initialized to true.
 * 2) Set i to 2.
 * 3) If i * i > N, halt.
 * 4) If is_prime[i] is false, go to step 9.
 * 5) Set j to i + i.
 * 6) Set is_prime[j] to false.
 * 7) Set j to j + i.
 * 8) If j <= N, go to step 6.
 * 9) Increment i. Go to step 3.

Steps 5 through 8 mark all multiples of prime $$i$$ as composite.

Pseudo-code
func sieve( integer N ) declare is_prime as a boolean array of size N.    for i = 1 to N do is_prime[i] = true is_prime[1] = false i = 2 while ( i * i <= N ) if ( is_prime[i] ) for j = i * i to N, in steps of i                     is_prime[j] = false i = i + 1 end func
 * Sieves up to N.
 * if is_prime[i] is true, then i is a prime.

Optimizations

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

Implementations
Implementation in C