Skip to content

Commit 754bf6c

Browse files
authored
Add Goldbach's Conjecture algorithm (#6127)
1 parent 39122a9 commit 754bf6c

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.thealgorithms.maths;
2+
3+
import static com.thealgorithms.maths.PrimeCheck.isPrime;
4+
5+
/**
6+
* This is a representation of the unsolved problem of Goldbach's Projection, according to which every
7+
* even natural number greater than 2 can be written as the sum of 2 prime numbers
8+
* More info: https://en.wikipedia.org/wiki/Goldbach%27s_conjecture
9+
* @author Vasilis Sarantidis (https://github.com/BILLSARAN)
10+
*/
11+
12+
public final class GoldbachConjecture {
13+
private GoldbachConjecture() {
14+
}
15+
public record Result(int number1, int number2) {
16+
}
17+
18+
public static Result getPrimeSum(int number) {
19+
if (number <= 2 || number % 2 != 0) {
20+
throw new IllegalArgumentException("Number must be even and greater than 2.");
21+
}
22+
23+
for (int i = 0; i <= number / 2; i++) {
24+
if (isPrime(i) && isPrime(number - i)) {
25+
return new Result(i, number - i);
26+
}
27+
}
28+
throw new IllegalStateException("No valid prime sum found."); // Should not occur
29+
}
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.thealgorithms.maths;
2+
3+
import static com.thealgorithms.maths.GoldbachConjecture.getPrimeSum;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
public class GoldbachConjectureTest {
10+
@Test
11+
void testValidEvenNumbers() {
12+
assertEquals(new GoldbachConjecture.Result(3, 7), getPrimeSum(10)); // 10 = 3 + 7
13+
assertEquals(new GoldbachConjecture.Result(5, 7), getPrimeSum(12)); // 12 = 5 + 7
14+
assertEquals(new GoldbachConjecture.Result(3, 11), getPrimeSum(14)); // 14 = 3 + 11
15+
assertEquals(new GoldbachConjecture.Result(5, 13), getPrimeSum(18)); // 18 = 5 + 13
16+
}
17+
@Test
18+
void testInvalidOddNumbers() {
19+
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(7));
20+
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(15));
21+
}
22+
@Test
23+
void testLesserThanTwo() {
24+
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(1));
25+
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(2));
26+
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(-5));
27+
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(-26));
28+
}
29+
}

0 commit comments

Comments
 (0)