【題解】ZeroJudge d307: 00686 – Goldbach’s Conjecture (II)

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=d307
【解題想法】質數表

  • 【原題】Goldbach’s Conjecture: For any even number n greater than or equal to 4, there exists at least one pair of prime numbers p1 and p2 such that n = p1 + p2.
  • 先建立指數表,再查詢 (i, n-i) 是否均為質數。
#include <iostream>
using namespace std;
const int maxn = 33000; //2^15 = 32 * 1024 = 32768
int prime[maxn];

int main() {
    //建立指數表
    for (int i = 2; i < maxn; i++){
        if (prime[i] == 0){
            for (int j = i+i; j < maxn; j+=i){
                prime[j] = 1;
            }
        }
    }
    int n;
    while (cin >> n){
        if (n == 0) break;
        int cnt = 0;
        for (int i = 2; i <= n / 2; i++){
            if (!prime[i] && !prime[n-i]){
                cnt++;
            }
        }
        cout << cnt << "\n";
    }
    return 0;
}
分享本文 Share with friends