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

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;

直接从1到n/2遍历的话会超时。所以遍历所有的素数找n-p[i]是否为素数。

#include<map>
#include<stack>
#include<queue>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define maxn 10000001
#define maxm 1000000000005
#define mod 1000000007
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
bool vis[maxn];
int p[1000000];
int tot;
void getp(){
    tot=0;
    mem(vis,true);
    vis[1]=vis[0]=false;
    for(ll i=2;i<=maxn;i++){
        if(vis[i]){
            p[tot++]=i;
            for(ll j=i*i;j<=maxn;j+=i)vis[j]=false;
        }
    }
}
int main(){
    getp();
    int t,test=0;scanf("%d",&t);
    while(t--){
        int x;scanf("%d",&x);
        int ans=0;
        for(int i=0;i<tot&&p[i]<=x/2;i++){
            if(vis[x-p[i]])
            ans++;
        }
      printf("Case %d: %d\n",++test,ans);
    }
}




posted @ 2018-05-11 16:35  _大美  阅读(142)  评论(0编辑  收藏  举报