Skip to content

Adding Egyptian Fraction Greedy Algorithm #5879

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 4 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,40 @@
package com.thealgorithms.greedyalgorithms;

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

import java.util.List;

public class EgyptianFractionTest {
EgyptianFraction ef = new EgyptianFraction();

@Test
public void testGetEgyptianFraction_NormalCase() {
List<String> result = ef.getEgyptianFraction(5, 6);
assertEquals(List.of("1/2", "1/3"), result);
}

@Test
public void testGetEgyptianFraction_SimpleFraction() {
List<String> result = ef.getEgyptianFraction(1, 2);
assertEquals(List.of("1/2"), result);
}

@Test
public void testGetEgyptianFraction_WholeNumber() {
List<String> result = ef.getEgyptianFraction(2, 1);
assertEquals(List.of("1/1", "1/2", "1/3", "1/6"), result); // Example output
}

@Test
public void testGetEgyptianFraction_OneOverOne() {
List<String> result = ef.getEgyptianFraction(1, 1);
assertEquals(List.of("1/1"), result);
}

@Test
public void testGetEgyptianFraction_OneOverThree() {
List<String> result = ef.getEgyptianFraction(1, 3);
assertEquals(List.of("1/3"), result);
}
}
Loading