题目链接:https://vjudge.net/problem/LightOJ-1259
Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 |
Output for Sample Input |
2 6 4 |
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, ...
题意:
哥德巴赫猜想:任何一个大于2的偶数,都可以是两个素数的和。给出一个偶数,判断有多少对素数的和是这个数。
题解:
由于n<=1e7,所以我们可以先筛选出1e7范围内的素数,然后再枚举每一个素数进行判断。
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <vector> 6 #include <cmath> 7 #include <queue> 8 #include <stack> 9 #include <map> 10 #include <string> 11 #include <set> 12 using namespace std; 13 typedef long long LL; 14 const int INF = 2e9; 15 const LL LNF = 9e18; 16 const int MOD = 1e9+7; 17 const int MAXN = 1e7+10; 18 19 bool notprime[MAXN]; 20 int prime[1000010]; 21 void getPrime() 22 { 23 memset(notprime, false, sizeof(notprime)); 24 notprime[0] = notprime[1] = true; 25 prime[0] = 0; 26 for (int i = 2; i<=MAXN; i++) 27 { 28 if (!notprime[i])prime[++prime[0]] = i; 29 for (int j = 1; j<=prime[0 ]&& prime[j]<=MAXN/i; j++) 30 { 31 notprime[prime[j]*i] = true; 32 if (i%prime[j] == 0) break; 33 } 34 } 35 } 36 37 int main() 38 { 39 getPrime(); 40 int T, n, kase = 0; 41 scanf("%d",&T); 42 while(T--) 43 { 44 scanf("%d",&n); 45 int ans = 0; 46 for(int i = 1; prime[i]<=n/2; i++) 47 if(!notprime[n-prime[i]]) 48 ans++; 49 printf("Case %d: %d ", ++kase,ans); 50 } 51 return 0; 52 }