素数筛法
线性筛更快。
1.埃氏筛法
1 int m=sqrt(n+0.5); 2 memset(vis,0,sizeof(vis)); 3 for(int i=2;i<=m;i++) 4 if(!vis[i]) 5 for(int j=i*i;j<=n;j+=i) 6 vis[j]=1;
Input
Output
Sample Input
Sample Output
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include<cmath> 6 using namespace std; 7 int n; 8 int vis[16005]; 9 void prime() 10 { 11 int m=sqrt(16000+0.5); 12 memset(vis,0,sizeof(vis)); 13 for(int i=2;i<=m;i++) 14 if(!vis[i]) 15 for(int j=i*i;j<=16000;j+=i) 16 vis[j]=1; 17 vis[1]=vis[2]=1; 18 } 19 int main() 20 { 21 prime(); 22 //printf("%d 123213",vis[4]); 23 int cnt=0; 24 while(~scanf("%d",&n)) 25 { 26 if(n<=0) 27 break; 28 printf("%d: ",++cnt); 29 if(vis[n]==0) 30 printf("yes\n"); 31 if(vis[n]==1) 32 printf("no\n"); 33 } 34 return 0; 35 } 36 //1 37 //2 38 //3 39 //4 40 //5 41 //17 42 //0
2.线性筛
1 memset(vis,false,sizeof(vis)); 2 tot=0; 3 for(int i=2;i<=maxn;i++) 4 { 5 if(!vis[i]) 6 prime1[tot++]=i; 7 for(int j=0;j<tot;j++) 8 { 9 if(i*prime1[j]>maxn) 10 break; 11 vis[i*prime1[j]]=true; 12 if(i%prime1[j]==0) 13 break;
Description
Goldbach's conjecture is one of the oldest unsolved problems in number theory and in all of mathematics. It states:
Every even integer, greater than 2, can be expressed as the sum of two primes [1].
Now your task is to check whether this conjecture holds for integers up to 107.
Input
Input starts with an integer T (≤ 300), denoting the number of test cases.
Each case starts with a line containing an integer n (4 ≤ n ≤ 107, n is even).
Output
For each case, print the case number and the number of ways you can express n as sum of two primes. To be more specific, we want to find the number of (a, b) where
1) Both a and b are prime
2) a + b = n
3) a ≤ b
Sample Input
2
6
4
Sample Output
Case 1: 1
Case 2: 1
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include<cmath> 6 using namespace std; 7 #define maxn 10000000 8 bool vis[10000002]; 9 int prime1[1000020]; 10 int tot; 11 void prime() 12 { 13 memset(vis,false,sizeof(vis)); 14 tot=0; 15 for(int i=2;i<=maxn;i++) 16 { 17 if(!vis[i]) 18 prime1[tot++]=i; 19 for(int j=0;j<tot;j++) 20 { 21 if(i*prime1[j]>maxn) 22 break; 23 vis[i*prime1[j]]=true; 24 if(i%prime1[j]==0) 25 break; 26 } 27 } 28 } 29 int main() 30 { 31 32 int t,n; 33 int ha=0; 34 scanf("%d",&t); 35 prime(); 36 while(t--) 37 { 38 int cnt=0; 39 scanf("%d",&n); 40 printf("Case %d: ",++ha); 41 for(int i=0;prime1[i]<=n/2;i++) 42 if(!vis[n-prime1[i]]) 43 cnt++; 44 printf("%d\n",cnt); 45 46 } 47 return 0; 48 }