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

本文探讨了哥德巴赫猜想,并提供了两种C语言实现方案来验证该猜想对于小于一百万的所有偶数是否成立。一种方案考虑所有素数,另一种则专注于奇素数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注:这题似乎有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[N],prime[N],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[N],prime[N],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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值