Monday, December 23, 2013

Seive Algorithm

#include <stdio.h>
#include <math.h>
#define N 1000000

static char P[N];

int main() {
    int  n, s, t, SQR = sqrt(N);                    
 
    P[0] = P[1] = 0
    for(n = 2; n <= N; n++)      
       P[n] = 1;

    for(n = 2; n <= SQR; n++)       
       if(P[n])                    
          for(s = 2, t = N/n; s <= t; s++) 
             P[s*n] = 0;

    for(n = 2, t = 0; n <= 100; n++)
       if(P[n])
          printf("%d ", n);

    return 0;
}

No comments:

Post a Comment