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

zoj 1951 Goldbach's Conjecture(素数筛选继续水)

2015-08-01 14:51 477 查看
注:这题似乎有bug, two odd prime numbers 不应该是奇素数吗,所以若输入7,应该是不可以拆的,可是输出“7 = 2 + 5”和"Goldbach's conjecture is wrong.\n"都可以AC,有知道的希望能解答下疑惑

Goldbach's Conjecture

Time Limit: 2 Seconds Memory Limit: 65536 KB

In 1742, Christian Goldbach, a German amateur mathematician, sent a letter to Leonhard Euler in which he made the following conjecture:

Every even number greater than 4 can be

written as the sum of two odd prime numbers.

For example:

8 = 3 + 5. Both 3 and 5 are odd prime numbers.

20 = 3 + 17 = 7 + 13.

42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23.

Today it is still unproven whether the conjecture is right. (Oh wait, I have the proof of course, but it is too long to write it on the margin of this page.)

Anyway, your task is now to verify Goldbach's conjecture for all even numbers less than a million.

思路:直接素数筛选预处理,然后枚举,我把素数也开了个数组存起来了,这样枚举的话应该是可以优化时间的。

因为题目存在bug,所以我两个代码都贴下:都可AC(C语言)

1:拆成两素数

#include<stdio.h>
#include<string.h>
#define N 1000010
int p
,prime
,tot=0;
void Prime(){
int i,j;
memset(prime,0,sizeof(prime));
prime[0]=prime[1]=1;
for(i=2;i<N;i++){
if(!prime[i]){
p[tot++]=i;
for(j=i+i;j<N;j+=i)
prime[j]=1;
}
}
}
int main(){
int n,i,j,ok;
Prime();
while(scanf("%d",&n)!=EOF){
if(n==0) break;
ok=0;
for(i=0;i<tot&&p[i]<=n/2;i++){
if(prime[n-p[i]]==0){
ok=1;
break;
}
}
if(ok) printf("%d = %d + %d\n",n,p[i],n-p[i]);
else printf("Goldbach's conjecture is wrong.\n");
}
return 0;
}


2:拆成两奇素数
#include<stdio.h>
#include<string.h>
#define N 1000010
int p
,prime
,tot=0;
void Prime(){
int i,j;
memset(prime,0,sizeof(prime));
prime[0]=prime[1]=1;
for(i=2;i<N;i++){
if(!prime[i]){
p[tot++]=i;
for(j=i+i;j<N;j+=i)
prime[j]=1;
}
}
}
int main(){
int n,i,j,ok;
Prime();
while(scanf("%d",&n)!=EOF){
if(n==0) break;
ok=0;
for(i=1;i<tot&&p[i]<=n/2;i++){
if(prime[n-p[i]]==0){
ok=1;
break;
}
}
if(ok) printf("%d = %d + %d\n",n,p[i],n-p[i]);
else printf("Goldbach's conjecture is wrong.\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: