|
| 1 | +package com.thealgorithms.greedyalgorithms; |
| 2 | +import java.util.ArrayList; |
| 3 | +import java.util.List; |
| 4 | +// Problem Link: https://en.wikipedia.org/wiki/Greedy_algorithm_for_Egyptian_fractions |
| 5 | + |
| 6 | +public class EgyptianFraction { |
| 7 | + // Function to decompose a fraction into a sum of unit fractions |
| 8 | + public static List<String> getEgyptianFraction(int numerator, int denominator) { |
| 9 | + List<String> result = new ArrayList<>(); |
| 10 | + |
| 11 | + while (numerator != 0) { |
| 12 | + // Find the smallest unit fraction that can be subtracted |
| 13 | + if (denominator % numerator == 0) { |
| 14 | + result.add("1/" + (denominator / numerator)); |
| 15 | + break; |
| 16 | + } |
| 17 | + int x = denominator / numerator + 1; |
| 18 | + |
| 19 | + result.add("1/" + x); |
| 20 | + // Update numerator and denominator for the next iteration |
| 21 | + numerator = numerator * x - denominator; |
| 22 | + denominator = denominator * x; |
| 23 | + |
| 24 | + // Reduce the fraction by dividing numerator and denominator by their gcd |
| 25 | + int gcd = gcd(numerator, denominator); |
| 26 | + numerator /= gcd; |
| 27 | + denominator /= gcd; |
| 28 | + } |
| 29 | + |
| 30 | + return result; |
| 31 | + } |
| 32 | + |
| 33 | + private static int gcd(int a, int b) { |
| 34 | + if (b == 0) |
| 35 | + return a; |
| 36 | + return gcd(b, a % b); |
| 37 | + } |
| 38 | + |
| 39 | + public static void main(String[] args) { |
| 40 | + int numerator = 5; |
| 41 | + int denominator = 6; |
| 42 | + |
| 43 | + List<String> egyptianFractions = getEgyptianFraction(numerator, denominator); |
| 44 | + |
| 45 | + System.out.println("Egyptian Fraction representation of " + numerator + "/" + denominator + " is:"); |
| 46 | + for (String frac : egyptianFractions) { |
| 47 | + System.out.print(frac + " "); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | + |
0 commit comments