LightOJ-1259-Goldbach`s Conjecture-素数打表+判断素数对数
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
Note
- An integer is said to be prime, if it is divisible by exactly two different integers. First few primes are 2, 3, 5, 7, 11, 13, ...
- 题意:给出n个数,判断每个数由几对素数组成
- 注意:pri开数组的范围
打表标记用bool,不然一直RT
判断素数对数当走到n/2时后面肯定找不到一对了,这个时候可以break了
判断有几对素数:
for(int i=0; i<p; i++) { if(pri[i]>n/2) break; if(book[n-pri[i]]==0) ans++; }
1 #include<stdio.h> 2 #include<cmath> 3 #include<algorithm> 4 #include<string.h> 5 typedef long long ll; 6 using namespace std; 7 8 //const int N=1e7+20; 9 bool book[10000001]; 10 int pri[5000000]; 11 int p; 12 13 void prime() 14 { 15 //非素数标记为1 16 //memset(book,0,sizeof(book)); 17 // memset(pri,0,sizeof(pri));这里自己会清空,不要随便去清空,耗时 18 book[0]=1; 19 book[1]=1; 20 p=0; 21 for(int i=2; i<=10000000; i++) 22 { 23 if(book[i]==0) 24 { 25 pri[p++]=i;//记录素数元素 26 for(int j=i*2; j<=10000000; j+=i) 27 book[j]=1; 28 } 29 } 30 } 31 32 int main() 33 { 34 prime(); 35 // sort(pri,pri+p); 36 int t,tt=1; 37 scanf("%d",&t); 38 int n; 39 while(t--) 40 { 41 scanf("%d",&n); 42 int ans=0; 43 for(int i=0; i<p; i++) 44 { 45 if(pri[i]>n/2) 46 break; 47 if(book[n-pri[i]]==0) 48 ans++; 49 } 50 printf("Case %d: %d\n",tt++,ans); 51 } 52 return 0; 53 }