Luogu C++ language | P1304 Goldbach's conjecture

Learn C++ from a young age! Record the questions asked during the Luogu C++ learning and exam preparation process, and record every moment.

Attached is a summary post: Luogu’s C++ language | Summary_The blog of a communicator who loves programming-CSDN blog


[Title description]

Enter an even number  N and verify whether all even numbers from 4 to N  conform to Goldbach's conjecture: any even number greater than 2 can be written as the sum of two prime numbers. If a number has more than one division method, output the solution with the smallest first addend compared to other division methods. For example, 10, 10=3+7=5+5, then 10=5+5 is the wrong answer.

【enter】

Enter a positive even number  N in the first line

【Output】

Output ( N −2)/2 lines. For row  i  :

First, output the positive even number 2 i +2, then output the equal sign, and then output the two prime numbers whose sum is 2 i +2 and whose first addend is the smallest, separated by a plus sign.

【Input sample】

10

【Output sample】

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

[Detailed code explanation]

#include <bits/stdc++.h>
using namespace std;
bool prime(int n) {
    if (n<=1) return false;
    for (int i=2; i<=sqrt(n); i++) {
        if (n%i==0) return false;
    }
    return true;
}
void gold(int n)
{
    for (int i=2; i<=n; i++) {
        if (prime(i) && prime(n-i)) {
            printf("%d=%d+%d\n", n, i, n-i);
            return;
        }
    }
}
int main()
{
    int n;
    cin >> n;
    for (int i=4; i<=n; i+=2) {
        gold(i);
    }
    return 0;
}

【operation result】

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

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/132839595