Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number. A solution will always exist as per Goldbach’s conjecture. If there are multiple solutions possible, return the lexicographically smaller solution. If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, then [a, b] < [c, d] if and only if a < c or a == c and b < d.
Method 1 - Using Goldbach’s conjecture and Sieve of Eratosthenes#
The approach is based on Goldbach’s conjecture that every even number greater than 2 can be expressed as the sum of two prime numbers. We’ll generate all prime numbers up to the given number using the Sieve of Eratosthenes technique and check pairs of these primes to find the required pair that sums up to the given number.
Here is the approach:
Generate Prime Numbers: Use the Sieve of Eratosthenes to generate a list of prime numbers up to the given number.
Find Prime Pair: Iterate over the list of prime numbers and for each prime p, check if number - p is also a prime.
Return Lexicographically Smallest Pair: Ensure the pair [a, b] such that a <= b is the lexicographically smallest pair found.
classSolution:
deffindPrimePairSum(self, n: int):
is_prime = self.sieve_of_eratosthenes(n)
for i in range(2, n //2+1):
if is_prime[i] and is_prime[n - i]:
return i, n - i
returnNonedefsieve_of_eratosthenes(self, n: int):
is_prime = [True] * (n +1)
is_prime[0] = is_prime[1] =False p =2while p * p <= n:
if is_prime[p]:
for i in range(p * p, n +1, p):
is_prime[i] =False p +=1return is_prime
# Example usagesolution = Solution()
n =10result = solution.findPrimePairSum(n)
print(f"{result[0]} + {result[1]} = {n}")