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.

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

 * Use a bit array instead of a boolean array to reduce memory usage.
 * On 32-bit platforms (like Intel x86), it's a good idea to use a 32-bit integer type in implementing the bit array.
 * Don't store the bits, representing even numbers -- they're all composites anyway (except for 2, of course.)

The C program below incorporates these tricks to compute the number of primes below 10^8. (The correct answer is 5761455.)

/* This code is in public domain. Use for whatever purpose at your own risk. */
 * 1) include 
 * 2) include 

/* The code assumes, that sizeof(unsigned)==4 */


 * 1) define MAXN 100000000  /* maximum value of N */
 * 2) define P1   1562501    /* = ceil(MAXN/64) */
 * 3) define P2   50000000   /* = ceil(MAXN/2) */
 * 4) define P3   5000       /* = ceil(ceil(sqrt(MAXN))/2) */

unsigned sieve[P1];


 * 1) define GET(b) ((sieve[(b)>>5]>>((b)&31))&1)

void make {   register unsigned i, j, k;    memset(sieve, 0, sizeof(sieve)); for (k = 1; k <= P3; k++) if (GET(k)==0) for(j=2*k+1,i=2*k*(k+1);i>5]|=1<<(i&31); }

int isprime(int p) { return p==2 || (p>2 && (p&1)==1 && (GET((p-1)>>1)==0)); }

int main {   int i, n;    make; for (n = 0, i = 0; i <= MAXN; i++) if (isprime(i)) n++; printf("The number of primes below 10^8 is %d.\n", n); return 0; }