您的位置:首页 > 编程语言 > Go语言

LightOJ - 1259 Goldbach`s Conjecture【素数筛+枚举】

2017-08-15 10:33 225 查看

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

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

可以先用素数筛筛出1e7以内的素数,标记并存起来。显然在这里1e6都存的下,如果直接开1e7的话会内存超限。枚举的时候也有一些小技巧。可以枚举<=n/2以内的素数,然后判断n-prime[i]是否为素数就好了,这样不会超时。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAX_N 10000000
int prime[MAX_N/10];
bool is_prime[MAX_N+1];
void sieve(int n)
{
int p = 0;
memset(is_prime,true,sizeof(is_prime));
is_prime[0] = is_prime[1] = false;
for(int i = 2; i <= n/2; i++)
{
if(is_prime[i])
prime[p++] = i;
for(int j=0; j<p && prime[j]*i<=n; j++)
{
is_prime[prime[j]*i]=false;
if(i%prime[j]==0)
break;
}
}
// for(int i=0;i<10000;i++)
// printf("%d ",prime[i]);
}
int main()
{
int t;
sieve(MAX_N);
scanf("%d",&t);
for(int tt=1; tt<=t; tt++)
{
int n,sum=0;
scanf("%d",&n);
for(int i=0;prime[i]<=n/2;i++)
{
if(is_prime[n-prime[i]])
sum++;
}
printf("Case %d: %d\n",tt,sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息