The sieve prime method is a fast method to find all prime numbers less than N, and the time is very short.
accomplish
We first use the simulation method to find all prime numbers within 10000:
for(i=2;i<10000;i++) { for(j=2;j<=i/2;j++) { if(i%j==0) //If i is divisible by the number j less than it, then i must not be prime break; } if(j>i/2) printf("%d ",i); }
Use the sieve method below:
const int N=10001; int p[N]; memset(p,0,sizeof(p)); //The initialization is all 0, 1 means it is not a prime number p[0]=p[1]=1; for(i=2;i<N;i++) { if(!p[i]) //If the current p[i] of i is not 0, i.e. i is a prime number { for(j=i+i;j<N;j+=i) //Then all multiples of i must not be prime numbers, so all their multiples are marked as 1 p[j]=1; } } for(i=0;i<N;i++) //Print a prime number, 0 means it is a prime number { if(!p[i]) printf("%d ",i); }
Compared with the simulation method, the time complexity of the sieve method is close to O(n) from O(n*n).