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(10的7次方).

输入:

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).

输出:

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

样例输入:

2

6

4

样例输出:

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, ...

大体题意就是让你找出一个数可以由多少组素数相加得到的组数

最开始的时候用int型判断素数,是素数return 0,不是素数return 1,这样最后会Memory Limit,所以就得用bool型,int 是4个字节的,bool是一个字节的。这样之后提交还是超出限制,就要找个数组把所有的素数存下来,所有的素数应该小于10000000/2个的,这样时间就减少了

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define maxn 10000000
bool isprime[maxn];
int a[5000000];
int num=1;
void getprime()//把所有的素数存下来,不是素数的标记为true
{
    memset(isprime,false,sizeof(isprime));
    isprime[0]=isprime[1]=true;
    for(int i=2;i<=maxn;i++)
    {

        if(!isprime[i])
        {
            a[num++]=i;
            for(int j=2*i;j<=maxn;j+=i)
                isprime[j]=true;
        }


    }
}
int main()
{
    int t;
    int ans=1;
    scanf("%d",&t);
    getprime();
    while(t--)
    {
        int sum=0;
        int n;
       scanf("%d",&n);
        for(int i=1;i<num;i++)
        {
            if(a[i]>=n/2+1)//因为是要两个素数之和,如果大于一半了继续判断就重复了(解释一下这里一半加1的原因,例如5,5/2取整是2,加1就是3,一开始2,3是一组了,肯定是不能重复的,所以当下一个遍历3的时候,另一个数就是2了,这一组我们是不要的,所以遍历到3的时候就直接break了,这里也可以写成a[i]>n/2)
            {
                break;
            }
            if(!isprime[n-a[i]])
                sum++;
    }
    printf("Case %d: %d\n",ans++,sum);
}
return 0;
}
 

猜你喜欢

转载自blog.csdn.net/zhangjinlei321/article/details/81591854
今日推荐