题目:https://vjudge.net/contest/242286#problem/A
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
1. 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,只需要找一个比n/ 2小的,一个大的,我们可以实现大个表,存下[1,10000007]所有素数,之后在里边找;不过用欧氏筛需要做一步优化,在找B的时候需要改一下,因为prime[]里边存的就是素数,所以限制条件可以用它,时间会缩短。
#include <iostream>
#include <stdio.h>
#include <string.h>
#define MAXN 10000005
using namespace std;
int N;
bool isprime[MAXN+1];
int prime[MAXN/10], tot; //防止MLE
void getPrime() {
memset(isprime, true, sizeof(isprime));
isprime[0] = isprime[1] = false;
tot = 0;
for(int i = 2; i < MAXN; i++) {
if(isprime[i]) prime[tot++] = i;
for(int j = 0; j < tot && prime[j] <= MAXN / i; j++) {
isprime[i * prime[j]]=false;
if(i % prime[j] == 0) break;
}
}
}
int main()
{
getPrime();
int t;
int Case=0;
scanf("%d",&t);
while(t--)
{
int cnt=0;
int b;
scanf("%d",&N);
for(int i=0;prime[i]<=N/2;i++)//用欧拉筛,需要优化这里。
{
b=N-prime[i];
if(isprime[b])cnt++;
}
printf("Case %d: %d\n",++Case,cnt);
}
return 0;
}