PTA实验4-2-3 验证“哥德巴赫猜想” (20分)

时间:2023-03-08 19:15:57

实验4-2-3 验证“哥德巴赫猜想” (20分)

数学领域著名的“哥德巴赫猜想”的大致意思是:任何一个大于2的偶数总能表示为两个素数之和。比如:24=5+19,其中5和19都是素数。本实验的任务是设计一个程序,验证20亿以内的偶数都可以分解成两个素数之和。

输入格式:
输入在一行中给出一个(2, 2 000 000 000]范围内的偶数N。

输出格式:
在一行中按照格式“N = p + q”输出N的素数分解,其中p ≤ q均为素数。又因为这样的分解不唯一(例如24还可以分解为7+17),要求必须输出所有解中p最小的解。

输入样例:

24

输出样例:

24 = 5 + 19

错解

双向链表构造素数表

原因:
1.构造素数表存储了过多的无关数据,导致内存溢出

2.判断素数的算法时间复杂度太大,导致运行超时PTA实验4-2-3 验证“哥德巴赫猜想” (20分)

正解:用两个单独的int存储头尾值,边运算边判断
PTA实验4-2-3 验证“哥德巴赫猜想” (20分)
改进判断素数的算法,时间复杂度从O(N^3)降到了O(sqrt(n)),解决了运行超时问题

代码中的素数判断操作用到了这篇博客里面的算法

//验证“哥德巴赫猜想”
#include <stdio.h>
#include <math.h> int check(int x); int main (void)
{
int start = 2;
int end;
int n;
int i=0;
scanf("%d", &n);
end = n-1;
while(start<=end){
if(start+end==n){
printf("%d = %d + %d", n, start, end);
break;
}
if(start+end>n){
do{
if(end==3){
end--;
}else{
end -= 2;
}
}while(check(end));
}else if(start+end<n){
do{
i++;
start = 2*i+1;
}while(check(start));
}
}
return 0;
} int check(int x)
{
int i;
int tmp;
if(x==2 || x==3){
return 0;
}
if(x%6 != 1 && x%6 != 5){
return 1;
}
tmp = sqrt(x);
for(i=5;i<=tmp;i+=6){
if(x%i==0 || x%(i+2)==0){
return 1;
}
} return 0;
}