Baekjoon - Goldbach's Conjecture

Ji Kim·2020년 9월 4일
0

Algorithm

목록 보기
17/34

Baekjoon : Goldbach's Conjecture

Description

Verify Goldbach's conjecture for all even numbers less than a million.

Goldbach's Conjecture

"Every even number greater than 4 can be written as the sum of two odd prime numbers."

Example

8 = 3 + 5
20 = 3 + 17 = 7 + 13
42 = 5 + 37 = 11 + 31 = 13 + 29 = 19 + 23

Input

8
20
42
0

Output

8 = 3 + 5
20 = 3 + 17
42 = 5 + 37

Approach

If simply implement the algorithm of Sieve of Eratosthenes and filter only through the odd prime numbers, the problem can be easily solved

Solution

#include <iostream>
using namespace std;
int N; 
bool prime[1000001];
 
int main()
{
    ios_base :: sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    for (int i = 2; i <= 1000001; i++)
    {
        if (!prime[i])
            for (int j = i + i; j <= 1000001; j = j + i) prime[j] = true;
    }  
 
    while(true)
    {
        cin >> N;

        if (N == 0) break;

        bool fail = true;
        for (int i = 3; i < 1000001; i = i + 2)
        {
            if (!prime[i] && !prime[N - i])
            {
                cout << N << " = " << i << " + " << N - i << "\n";
                fail = false;
                break;
            }
        }
        if (fail) cout << "Goldbach's conjecture is wrong." << "\n";
    }
 
    return 0;
}
profile
if this then that

0개의 댓글