素数筛模板(数学)
这是我找了好多找到素数筛优化的很不错的了 如果有大神知道还能再优化的话希望能提取宝贵意见 Orz
1 # include <map> 2 # include <queue> 3 # include <stack> 4 # include <math.h> 5 # include <stdio.h> 6 # include <string.h> 7 # include <iostream> 8 # include <algorithm> 9 using namespace std; 10 11 int a[1000010]; 12 13 int main(void) 14 { 15 int n; 16 while(~scanf("%d", &n) && n) 17 { 18 a[0] = 0, a[1] = 0, a[2] = 1; 19 for(int i = 3; i <= n; i++) 20 a[i] = i%2; 21 int k = floor(sqrt(n)+0.5); 22 for(int i = 3; i <= k; i++) 23 { 24 if(a[i]) 25 { 26 for(int j = 2*i; j <= n; j += i) 27 { 28 a[j] = 0; 29 } 30 } 31 } 32 int sum = 0; 33 for(int i = 1; i <= n; i++) 34 { 35 if(a[i]) 36 sum++; 37 } 38 printf("%d\n", sum); 39 } 40 41 return 0; 42 }