洛谷-P1304 哥德巴赫猜想

洛谷-P1304 哥德巴赫猜想

原题链接:https://www.luogu.com.cn/problem/P1304


题目描述

输入一个偶数 \(N(N<=10000)\),验证4~N所有偶数是否符合哥德巴赫猜想:任一大于 2 的偶数都可写成两个质数之和。如果一个数不止一种分法,则输出第一个加数相比其他分法最小的方案。例如 10,10=3+7=5+5,则 10=5+5 是错误答案。

输入格式

第一行N

输出格式

4=2+2 6=3+3 …… N=x+y

输入输出样例

输入 #1

10

输出 #1

4=2+2
6=3+3
8=3+5
10=3+7

C++代码

#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int m) {
    if (m == 0 || m == 1)
        return false;
    for (int i=2; i<=sqrt(m); ++i)
        if (m % i == 0)
            return false;
    return true;
}

int main() {
    int n;
    cin >> n;
    int a[n];
    for (int i=2; i<n; ++i)
        a[i] = isPrime(i)? 1: 0;
    for (int i=4; i<=n; i+=2)
        for (int j=2; j<i; ++j)
            if (a[j] && a[i-j]) {
                cout << i << '=' << j
                    << '+' << i-j << endl;
                break;
            }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/yuzec/p/13402620.html