素數判斷函數 `judge` 只檢查 `k=2` 能否整除就直接返回,邏輯錯誤:
bool judge(int x) {
for (int k = 2; k <= x/2; k++) {
if (x % k == 0) return false; // 發現因子即合數
}
return true; // 循環結束無因子才是素數
}
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n) {
if (n < 2) return false;
int limit = sqrt(n);
for (int i = 2; i <= limit; ++i)
if (n % i == 0) return false;
return true;
}
int main() {
const int MAX = 1000;
cout << "4 到 " << MAX << " 的偶數哥德巴赫分解:" << endl;
for (int n = 4; n <= MAX; n += 2) {
bool found = false;
for (int p = 2; p <= n/2; ++p) {
if (isPrime(p) && isPrime(n - p)) {
cout << n << " = " << p << " + " << (n-p) << endl;
found = true;
break; // 只輸出第一對
}
}
if (!found) cout << n << " 無分解(理論不應出現)" << endl;
}
return 0;
}
sqrt(n),而非 n/2。n/2,利用對稱性避免重復。修正素數判斷邏輯(循環全程檢查、正確返回),結合平方根優化,即可正確驗證哥德巴赫猜想在給定範圍內的成立情況。