Goldbach's Conjecture states that every even integer greater than or equal to 4 can be represented as the sum of two prime numbers. For a given even number $n$, we need to calculate the number of unique pairs $(p_1, p_2)$ such that $p_1 + p_2 = n$ and both $p_1, p_2$ are prime numbers.
Algorithmic Strategy
The maximum value for $n$ is $2^{15}$ (32,768). To solve this efficiently, we employ the following steps:
- Sieve of Eratosthenes: Pre-calculate all prime numbers up to 32,768. This allows for $O(1)$ verification of whether a specific number is prime during the calculation phase.
- Optimized Search: For a given even number $n$, we iterate through a lisst of pre-calculated primes $p$ such that $p \le n/2$. If the complement value $n - p$ is also a prime (checked via the boolean array from the sieve), we increment our counter.
By restricting the loop to $n/2$, we avoid double-counting pairs like $(3, 7)$ and $(7, 3)$, ensuring that only ditsinct combinations are counted.
Implementasion
The following C++ code implements the pre-calculation and search logic using standard library features for efficiency.
#include <iostream>
#include <vector>
const int LIMIT = 32768;
bool not_prime[LIMIT] = {false};
int primes[LIMIT];
int prime_count = 0;
void sieve() {
not_prime[0] = not_prime[1] = true;
for (int i = 2; i < LIMIT; ++i) {
if (!not_prime[i]) {
primes[prime_count++] = i;
for (long long j = 1LL * i * i; j < LIMIT; j += i) {
not_prime[j] = true;
}
}
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
sieve();
int target;
while (std::cin >> target && target != 0) {
int results = 0;
for (int i = 0; i < prime_count && primes[i] <= target / 2; ++i) {
int p1 = primes[i];
int p2 = target - p1;
if (!not_prime[p2]) {
results++;
}
}
std::cout << results << "\n";
}
return 0;
}
Complexity Analysis
- Preprocessing: The Sieve of Eratosthenes takes $O(N \log \log N)$ time, where $N = 32,768$.
- Query Processing: Each query takes $O(M)$ time, where $M$ is the number of primes less than $n$. Given $N$ is small, this process is nearly instantaneous.
- Space Complexity: We use $O(N)$ space to store the boolean prime table and the list of primes.