Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/main/java/com/thealgorithms/maths/GoldbachConjecture.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,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
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.thealgorithms.maths;

import static com.thealgorithms.maths.GoldbachConjecture.getPrimeSum;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

public class GoldbachConjectureTest {
@Test
void testValidEvenNumbers() {
assertEquals(new GoldbachConjecture.Result(3, 7), getPrimeSum(10)); // 10 = 3 + 7
assertEquals(new GoldbachConjecture.Result(5, 7), getPrimeSum(12)); // 12 = 5 + 7
assertEquals(new GoldbachConjecture.Result(3, 11), getPrimeSum(14)); // 14 = 3 + 11
assertEquals(new GoldbachConjecture.Result(5, 13), getPrimeSum(18)); // 18 = 5 + 13
}
@Test
void testInvalidOddNumbers() {
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(7));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(15));
}
@Test
void testLesserThanTwo() {
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(1));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(2));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(-5));
assertThrows(IllegalArgumentException.class, () -> getPrimeSum(-26));
}
}
Loading