哥德巴赫猜想
题目 哥德巴赫猜想
哥德巴赫猜想的内容如下:
任意一个大于 4 的偶数都可以拆成两个奇素数之和。
例如:
8=3+5 20=3+17=7+13 42=5+37=11+31=13+29=19+23
现在,你的任务是验证所有小于一百万的偶数能否满足哥德巴赫猜想。
输入格式 输入包含多组数据。
每组数据占一行,包含一个偶数 n。
读入以 0 结束。
输出格式 对于每组数据,输出形如 n=a+b,其中 a,b 是奇素数。
若有多组满足条件的 a,b,输出 b−a 最大的一组。
若无解,输出 Goldbach's conjecture is wrong.。
数据范围 6≤n<106
输入样例
8
20
42
0
输出样例:
8 = 3 + 5
20 = 3 + 17
42 = 5 + 37
思路分析
筛出所有的质数
从小到大枚举每个质数a 判断n-a是不是也是质数
要差值最大的一组 第一次找到的就是答案
代码实现
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
set<int> primes;
bool isnot_prime[N];
int n;
void get_primes(int n){
for(int i=2;i<=n;i++){
if(!isnot_prime[i]){
primes.insert(i);
for(int j=i;j<=n;j+=i)
isnot_prime[j]=true;
}
}
}
int main()
{
get_primes(N-1);
while(cin>>n,n){
for(auto a:primes){
if(a==2)//(注意 要放过数字2,因为2是偶数,本题要求是奇数)
continue;
int b=n-a;
if(primes.count(b)){
cout<<n<<" = "<< a <<" + "<< b <<endl;
break;
}
}
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int primes[N], cnt;
bool st[N];
void get_primes(int n) {
for (int i = 2; i <= n; i++) {
if (!st[i])
primes[cnt++] = i;
for (int j = 0; primes[j] * i <= n; j++) {
st[primes[j] * i] = true;
if (i % primes[j] == 0)
break;
}
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
get_primes(N - 1);
int n;
while (cin >> n, n) {
for (int i = 1;; i++) { // 枚举奇数质数 不用上界 默认哥德巴赫猜想正确 必有解
int a = primes[i]; //primes[0]=2,2是质数 偶数 本题要求奇数,放过数字2
int b = n - a;
if (!st[b]) {
printf("%d = %d + %d\n", n, a, b);
break;
}
}
}
return 0;
}
💬 评论