哥德巴赫猜想(难度:1颗星)

来源:互联网 发布:ajax post传递数组 编辑:程序博客网 时间:2024/06/05 09:15

问题描述:

哥德巴赫猜想的一种描述是,大于4的正偶数(我们假定1不是质数)都能分解成两个质数之和,我们假设这个猜想成立,我们现在输入一个大于4的正偶数N,输出所有能够满足哥德巴赫猜想的等式。(其中N的范围是【4,100000000】)

输入样例:
100

输出样例:
100 = 3 + 97
100 = 11 + 89
100 = 17 + 83
100 = 29 + 71
100 = 41 + 59
100 = 47 + 53

参考代码:

#include <stdio.h>#include <malloc.h>void FilterPrimer(char* pIsPrime, int n){//使用筛选法过滤掉不是质数的,这种是求某个范围内所有质数最快的方法,时间复杂度均摊是线性的    int i, j;    for (i = 2; i <= n; i++)        pIsPrime[i] = 1;//先假定所有的数都是质数    for (i = 2; i <= n; i++)    {        if (pIsPrime[i])        {//如果某个数是质数,则把它的倍数全部过滤掉            for (j = 2; j * i <= n; j++)                pIsPrime[j * i] = 0;        }    }}int main(){    int i, n, sum = 0;    printf("输入正偶数:");    scanf_s("%d", &n);    char *pIsPrime = (char*)malloc((n + 1) * sizeof(char));    FilterPrimer(pIsPrime, n);    for (i = 2; i <= n / 2; i++)        if (pIsPrime[i] && pIsPrime[n - i])            printf("%d = %d + %d\n", n, i, n - i);    return 0;}

运行结果:

这里写图片描述

原创粉丝点击