Egyptian Fraction

Every positive fraction can be represented as sum of unique unit fractions. A fraction is unit fraction if numerator is 1 and denominator is a positive integer, for example 1/3 is a unit fraction. Such a representation is called Egyptian Fraction as it was used by ancient Egyptians.

Following are few examples:

Egyptian Fraction Representation of 2/3 is 1/2 + 1/6
Egyptian Fraction Representation of 6/14 is 1/3 + 1/11 + 1/231
Egyptian Fraction Representation of 12/13 is 1/2 + 1/3 + 1/12 + 1/156
public class Solution {
    public void printEgyptian(int numerator, int denominator) {

        if (denominator == 0 || numerator == 0)
            return;

        if (denominator % numerator == 0) {
            System.out.print("1/" + denominator / numerator);
            return;
        }

        if (numerator % denominator == 0) {
            System.out.print(numerator / denominator);
            return;
        }

        if (numerator > denominator) {
            System.out.print(numerator / denominator + " + ");
            printEgyptian(numerator % denominator, denominator);
            return;
        }

        int n = denominator / numerator + 1;
        System.out.print("1/" + n + " + ");

        // Recur for remaining part
        // (num/den)-(1/n)
        printEgyptian(numerator * n - denominator, denominator * n);
    }
}

Last updated