Goldbach Pair
Problem
Goldbach's conjecture says that every even number n >= 4 is the sum of two primes. Read n and print the pair p q with the smallest p such that p and q are prime and p + q = n.
Constraints
- 4 <= n <= 10^5, n is even
Examples
Input
28
Output
5 23
Solutions
We test p = 2, 3, 4, ... and stop at the first p where both p and n - p are prime. The first p found is the smallest one. A prime test by trial division up to the square root is enough here.
/*
* Problem : Write an even number as the sum of two primes.
* Input : An even integer n >= 4.
* Output : Two primes p q with p <= q.
* Approach: Try the smallest prime first.
* Time : O(n sqrt n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This helper returns true if the number is prime.
static boolean isPrime(long x) {
if (x < 2) {
return false;
}
for (long d = 2; d * d <= x; d++) {
if (x % d == 0) {
return false;
}
}
return true;
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(long n) {
// Step 1: Try every p from 2 up to n / 2. The smaller number is never bigger than n / 2.
for (long p = 2; p <= n / 2; p++) {
// Step 2: Both p and n - p must be prime.
if (isPrime(p) && isPrime(n - p)) {
return new String[] {p + " " + (n - p)};
}
}
return new String[] {"none"};
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(String.join("\n", solve(n)));
}
}
Hints (1)
- Why is it enough to try p up to n / 2?