http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=1468
简单的素数筛选会超时,因为是多组,所以先打表会更快,这样就不用每次都筛选了。
1 #include <stdio.h> 2 #include <string.h> 3 #include <math.h> 4 const int N=1000002; 5 long long a[N]; 6 void printf_prime( ) 7 { 8 a[1] = 0; 9 a[2] = 1; 10 for (int i = 3; i < N; i ++) 11 { 12 a[i] = i%2; 13 } 14 for (int i = 3; i <= 1000; i ++) 15 { 16 if (a[i]) 17 { 18 for (int j = 2*i; j < N; j += i) 19 a[j] = 0; 20 } 21 } 22 } 23 int main() 24 { 25 int n,cnt; 26 printf_prime(); 27 while(~scanf("%d",&n)&&n) 28 { 29 cnt = 0; 30 for (int i = 1; i < n; i ++) 31 { 32 33 if (a[i]) 34 { 35 cnt++; 36 } 37 } 38 printf("%d ",cnt); 39 } 40 41 return 0; 42 }