Skip to content

Commit f2d93f9

Browse files
committed
feat: Add EgyptianFraction new algorithm with Junit tests
1 parent 9c76b30 commit f2d93f9

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Class to represent a fraction as a sum of unique unit fractions.
8+
* Example: 2/3 = 1/2 + 1/6
9+
*
10+
* @author Hardvan
11+
*/
12+
public final class EgyptianFraction {
13+
private EgyptianFraction() {
14+
}
15+
16+
/**
17+
* Calculates the Egyptian Fraction representation of a given fraction.
18+
*
19+
* @param numerator the numerator of the fraction
20+
* @param denominator the denominator of the fraction
21+
* @return List of unit fractions represented as strings "1/x"
22+
*/
23+
public static List<String> getEgyptianFraction(int numerator, int denominator) {
24+
List<String> result = new ArrayList<>();
25+
while (numerator != 0) {
26+
int x = (int) Math.ceil((double) denominator / numerator);
27+
result.add("1/" + x);
28+
numerator = numerator * x - denominator;
29+
denominator = denominator * x;
30+
}
31+
return result;
32+
}
33+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.List;
6+
import java.util.stream.Stream;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.Arguments;
9+
import org.junit.jupiter.params.provider.MethodSource;
10+
11+
public class EgyptianFractionTest {
12+
13+
@ParameterizedTest
14+
@MethodSource("fractionProvider")
15+
public void testGetEgyptianFraction(int numerator, int denominator, List<String> expected) {
16+
assertEquals(expected, EgyptianFraction.getEgyptianFraction(numerator, denominator));
17+
}
18+
19+
private static Stream<Arguments> fractionProvider() {
20+
return Stream.of(Arguments.of(2, 3, List.of("1/2", "1/6")), Arguments.of(3, 10, List.of("1/4", "1/20")), Arguments.of(1, 3, List.of("1/3")), Arguments.of(1, 2, List.of("1/2")), Arguments.of(4, 13, List.of("1/4", "1/18", "1/468")));
21+
}
22+
}

0 commit comments

Comments
 (0)