forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGoldbachConjecture.java
30 lines (25 loc) · 1.01 KB
/
GoldbachConjecture.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.thealgorithms.maths;
import static com.thealgorithms.maths.PrimeCheck.isPrime;
/**
* This is a representation of the unsolved problem of Goldbach's Projection, according to which every
* even natural number greater than 2 can be written as the sum of 2 prime numbers
* More info: https://en.wikipedia.org/wiki/Goldbach%27s_conjecture
* @author Vasilis Sarantidis (https://github.com/BILLSARAN)
*/
public final class GoldbachConjecture {
private GoldbachConjecture() {
}
public record Result(int number1, int number2) {
}
public static Result getPrimeSum(int number) {
if (number <= 2 || number % 2 != 0) {
throw new IllegalArgumentException("Number must be even and greater than 2.");
}
for (int i = 0; i <= number / 2; i++) {
if (isPrime(i) && isPrime(number - i)) {
return new Result(i, number - i);
}
}
throw new IllegalStateException("No valid prime sum found."); // Should not occur
}
}