It takes about 1000 ms to use the ordinary screening method, which is 0000 million.
#include <stdio.h>
#include <string.h>
#include <math.h>
char dp[10000010];
const int inf = 10000001;
int t = sqrt(inf);
inline void prime ( )
{
int i, j, k = 0,p;
dp[1] = -1;
for (i = 2; i <= t; i++)
if( dp[i] != -1)
{
//p = inf / i;
for (j = 2; j <= inf / i ; j ++)
dp[i * j] = -1;
}
}
int main( )
{
int N, k, i;
prime ( );
while(scanf("%d", &N) != EOF)
{
for (i =2; i < N; i++)
if (dp[i]!= -1)
printf("%d\n",i);
}
return 0;
}
The following screening method only requires around milliseconds. Powerful. You only need to open an array of 500 and 0000. Even numbers do not need to be screened. (Thanks Tao -_-).
#include <stdio.h>
#include <string.h>
#include <math.h>
int dp[5000010] = {0};
int main( )
{
int N,i, j, k, n;
while (scanf("%d", &N) != EOF ) {
n = sqrt( N +1);
for ( i = 3;i <= n; i += 2) {
if (dp[i >> 1])
continue;
int x = i << 1;
for( j = i * i; j <= N; j += x)
dp[j >> 1] = 1;
}
printf("2\n");
int t = (N +1) / 2;
for ( i = 1; i < t ; i++) {
if(dp[i])
continue;
printf("%d\n",(i << 1 )+ 1);
}
}
return 0;
}