void init_prim() { memset(visit, true, sizeof(visit)); int num = 0; for (int i = 2; i <= 1000000; ++i) { if (visit[i] == true) { num++; prime[num] = i; //mp[i]=num; } for (int j = 1; ((j <= num) && (i * prime[j] <= 1000000)); ++j) { visit[i * prime[j]] = false; if (i % prime[j] == 0) break; //点睛之笔 } } }
第一种更快 理解一下 看一个素数的题 hdu 2136
void init_prim() { memset(visit, true, sizeof(visit)); int num = 0; for (int i = 2; i <= 1000000; ++i) { for(int j=i+i;j<=1000000;j=j+i) visit[j]=false; } for(int i=2;i<=1000000;i++) if(visit[i]) { prime[++num]=i; //mp[i]=num; } }