Skip to content

Adding Egytian Fraction Greedy Algorithm #5877

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
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
Original file line number Diff line number Diff line change
@@ -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<String> getEgyptianFraction(int numerator, int denominator) {
List<String> 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);
}
}


Original file line number Diff line number Diff line change
@@ -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<String> result = ef.getEgyptianFraction(5, 6);
assertEquals(List.of("1/2", "1/3"), result);
}
}
Loading