筛法求素数
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 #include <cmath> 5 using namespace std; 6 7 #define REP(n) for(int o=0;o<n;o++) 8 9 const int maxn = 10000005; 10 bool is_prime[maxn]; 11 int prime_cnt[maxn]; 12 13 void prime() { 14 memset(is_prime,true,sizeof(is_prime)); 15 int len = (int)sqrt(maxn + 0.5); 16 for(int i = 2;i <= len;i++) 17 if(is_prime[i]) 18 for(int j = i*i;j < maxn;j += i) 19 is_prime[j] = false; 20 is_prime[1] = false; 21 22 23 prime_cnt[0] = 0; 24 for(int i = 1;i < maxn;i++) 25 prime_cnt[i] = prime_cnt[i - 1] + is_prime[i]; 26 } 27 28 int main() { 29 prime(); 30 31 int n; 32 while(scanf("%d",&n), n!= 0) { 33 printf("%d ",prime_cnt[n]); 34 } 35 36 return 0; 37 }