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

题意:

判断一个数是否能由两个素数相加得到,如果可以,写出有几组;

分析:

直接素数打表,然后判断n减去这个素数是否为素数即可;需要注意的是,素数打表的时候,我使用j=i*i的发现一直wr,改为j=2*i可以过,而且在记录素数时最好使用bool,否则会超限;

代码:

#include<stdio.h>
#include<math.h>
using namespace std;
#define maxn 10000010
bool p[maxn];
int prim[666666];
int t,k=0;
int n;
void primary()
{
    p[1]=1;
    for(int i=2;i<=maxn;i++)
    {
        if(!p[i])
        {
            prim[k++]=i;
            for(int j=i+i;j<=maxn;j+=i)
            {
                p[j]=1;
            }
        }
    }
    return ;
}
int main()
{
    int casee=0;
    scanf("%d",&t);
    primary();
    while(t--)
    {
        scanf("%d",&n);
        int ans=0;
        for(int i=0;i<k;i++)
        {
            if(prim[i]>=n/2+1)//因为是从小到大,因此只要这个素数大于n/2那就说明后面的不用判断了
                break;
            if(p[n-prim[i]]==0)
                ans++;
        }
        printf("Case %d: %d\n",++casee,ans);
    }
    return 0;
}
 

 

猜你喜欢

转载自blog.csdn.net/stdio_xuege/article/details/81168044
今日推荐