diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/EgyptianFraction.java b/src/main/java/com/thealgorithms/greedyalgorithms/EgyptianFraction.java new file mode 100644 index 000000000000..893097c3669d --- /dev/null +++ b/src/main/java/com/thealgorithms/greedyalgorithms/EgyptianFraction.java @@ -0,0 +1,31 @@ +package com.thealgorithms.greedyalgorithms; +import java.util.ArrayList; +import java.util.List; +// Problem Link: https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions + +public class EgyptianFraction { + + public List getEgyptianFraction(int numerator, int denominator) { + List fractions = new ArrayList<>(); + + // Loop until the numerator becomes zero + while (numerator != 0) { + // Find the smallest unit fraction + int x = (denominator + numerator - 1) / numerator; // Ceiling of (denominator / numerator) + fractions.add("1/" + x); + + // Update the numerator and denominator + numerator = numerator * x - denominator; + denominator = denominator * x; + } + + return fractions; + } + + private int gcd(int a, int b) { + if (b == 0) return a; // Compact if statement for readability + return gcd(b, a % b); + } +} + + diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java new file mode 100644 index 000000000000..951c3a5de08c --- /dev/null +++ b/src/test/java/com/thealgorithms/greedyalgorithms/EgyptianFractionTest.java @@ -0,0 +1,15 @@ +package com.thealgorithms.greedyalgorithms; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.List; + +public class EgyptianFractionTest { + @Test + public void testGetEgyptianFraction() { + EgyptianFraction ef = new EgyptianFraction(); + List result = ef.getEgyptianFraction(5, 6); + assertEquals(List.of("1/2", "1/3"), result); + } +}