Greedy Algorithm for Egyptian Fraction

21 Feb, 2022
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
We can generate Egyptian Fractions using Greedy Algorithm. For a given number of the form ‘nr/dr’ where dr > nr, first find the greatest possible unit fraction, then recur for the remaining part. For example, consider 6/14, we first find ceiling of 14/6, i.e., 3. So the first unit fraction becomes 1/3, then recur for (6/14 – 1/3) i.e., 4/42. Below is implementation of above idea. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print a fraction in Egyptian Form using Greedy// Algorithm#include <iostream>using namespace std; void printEgyptian(int nr, int dr){    // If either numerator or denominator is 0    if (dr == 0 || nr == 0)        return;     // If numerator divides denominator, then simple division    // makes the fraction in 1/n form    if (dr%nr == 0)    {        cout << "1/" << dr/nr;        return;    }     // If denominator divides numerator, then the given number    // is not fraction    if (nr%dr == 0)    {        cout << nr/dr;        return;    }     // If numerator is more than denominator    if (nr > dr)    {        cout << nr/dr << " + ";        printEgyptian(nr%dr, dr);        return;    }     // We reach here dr > nr and dr%nr is non-zero    // Find ceiling of dr/nr and print it as first    // fraction    int n = dr/nr + 1;    cout << "1/" << n << " + ";     // Recur for remaining part    printEgyptian(nr*n-dr, dr*n); } // Driver Programint main(){    int nr = 6, dr = 14;    cout << "Egyptian Fraction Representation of "         << nr << "/" << dr << " is\n ";    printEgyptian(nr, dr);    return 0;}
//Java program to print a fraction// in Egyptian Form using Greedy// Algorithm class GFG {     static void printEgyptian(int nr, int dr) {        // If either numerator or        // denominator is 0        if (dr == 0 || nr == 0) {            return;        }         // If numerator divides denominator,        // then simple division makes        // the fraction in 1/n form        if (dr % nr == 0) {            System.out.print("1/" + dr / nr);            return;        }         // If denominator divides numerator,        // then the given number is not fraction        if (nr % dr == 0) {            System.out.print(nr / dr);            return;        }         // If numerator is more than denominator        if (nr > dr) {            System.out.print(nr / dr + " + ");            printEgyptian(nr % dr, dr);            return;        }         // We reach here dr > nr and dr%nr        // is non-zero. Find ceiling of        // dr/nr and print it as first        // fraction        int n = dr / nr + 1;        System.out.print("1/" + n + " + ");         // Recur for remaining part        printEgyptian(nr * n - dr, dr * n);    } // Driver Code    public static void main(String[] args) {        int nr = 6, dr = 14;        System.out.print("Egyptian Fraction Representation of "                + nr + "/" + dr + " is\n ");        printEgyptian(nr, dr);    }} /*This code is contributed by Rajput-Ji*/
# Python3 program to print a fraction# in Egyptian Form using Greedy# Algorithm # import math package to use# ceiling functionimport math # define a function egyptianFraction# which receive parameter nr as# numerator and dr as denominatordef egyptianFraction(nr, dr):     print("The Egyptian Fraction " +          "Representation of {0}/{1} is".                format(nr, dr), end="\n")     # empty list ef to store    # denominator    ef = []     # while loop runs until    # fraction becomes 0 i.e,    # numerator becomes 0    while nr != 0:         # taking ceiling        x = math.ceil(dr / nr)         # storing value in ef list        ef.append(x)         # updating new nr and dr        nr = x * nr - dr        dr = dr * x     # printing the values    for i in range(len(ef)):        if i != len(ef) - 1:            print(" 1/{0} +" .                    format(ef[i]), end = " ")        else:            print(" 1/{0}" .                    format(ef[i]), end = " ") # calling the functionegyptianFraction(6, 14) # This code is contributed# by Anubhav Raj Singh
// C# program to print a fraction// in Egyptian Form using Greedy// Algorithmusing System; class GFG{static void printEgyptian(int nr, int dr){    // If either numerator or    // denominator is 0    if (dr == 0 || nr == 0)        return;     // If numerator divides denominator,    // then simple division  makes    // the fraction in 1/n form    if (dr % nr == 0)    {        Console.Write("1/" + dr / nr);        return;    }     // If denominator divides numerator,    // then the given number is not fraction    if (nr % dr == 0)    {        Console.Write(nr / dr);        return;    }     // If numerator is more than denominator    if (nr > dr)    {        Console.Write(nr / dr + " + ");        printEgyptian(nr % dr, dr);        return;    }     // We reach here dr > nr and dr%nr    // is non-zero. Find ceiling of    // dr/nr and print it as first    // fraction    int n = dr / nr + 1;    Console.Write("1/" + n + " + ");     // Recur for remaining part    printEgyptian(nr * n - dr, dr * n);} // Driver Codepublic static void Main(){    int nr = 6, dr = 14;    Console.Write( "Egyptian Fraction Representation of " +                                 nr + "/" + dr + " is\n ");    printEgyptian(nr, dr);}} // This code is contributed// by Akanksha Rai(Abby_akku)
<?php// PHP program to print a fraction// in Egyptian Form using Greedy// Algorithm function printEgyptian($nr, $dr){    // If either numerator or    // denominator is 0    if ($dr == 0 || $nr == 0)        return;     // If numerator divides denominator,    // then simple division makes the    // fraction in 1/n form    if ($dr % $nr == 0)    {        echo "1/", (int)$dr / $nr;        return;    }     // If denominator divides numerator,    // then the given number is not fraction    if ($nr%$dr == 0)    {        echo (int)($nr / $dr);        return;    }     // If numerator is more than denominator    if ($nr > $dr)    {        echo (int)($nr/$dr), " + ";        printEgyptian($nr % $dr, $dr);        return;    }     // We reach here dr > nr and dr%nr is    // non-zero. Find ceiling of dr/nr and    // print it as first fraction    $n = (int)($dr / $nr ) + 1;    echo "1/" , $n , " + ";     // Recur for remaining part    printEgyptian($nr * $n - $dr, $dr * $n);} // Driver Code$nr = 6;$dr = 14;echo "Egyptian Fraction Representation of ",                    $nr, "/", $dr, " is\n ";printEgyptian($nr, $dr);     // This code is contributed by ajit.?>
<script>    // Javascript program to print a fraction    // in Egyptian Form using Greedy    // Algorithm         function printEgyptian(nr, dr)    {        // If either numerator or        // denominator is 0        if (dr == 0 || nr == 0)            return;         // If numerator divides denominator,        // then simple division  makes        // the fraction in 1/n form        if (dr % nr == 0)        {            document.write("1/" + parseInt(dr / nr, 10));            return;        }         // If denominator divides numerator,        // then the given number is not fraction        if (nr % dr == 0)        {            document.write(parseInt(nr / dr, 10));            return;        }         // If numerator is more than denominator        if (nr > dr)        {            document.write(parseInt(nr / dr, 10) + " + ");            printEgyptian(nr % dr, dr);            return;        }         // We reach here dr > nr and dr%nr        // is non-zero. Find ceiling of        // dr/nr and print it as first        // fraction        let n = parseInt(dr / nr, 10) + 1;        document.write("1/" + n + " + ");         // Recur for remaining part        printEgyptian(nr * n - dr, dr * n);    }           let nr = 6, dr = 14;    document.write( "Egyptian Fraction Representation of " + nr + "/" + dr + " is\n ");    printEgyptian(nr, dr); // This code is contributed by divyeshrabadiya07.</script>
Output: 
Egyptian Fraction Representation of 6/14 is
 1/3 + 1/11 + 1/231 
The recursive solution in Python is as follows:
Python3
import math def getEgyptianFraction(numerator,denominator):    str = ""    output = getEgyptianFractionUtil(numerator,denominator,[])    for denom in output:        str += "1/{0} + ".format(denom);    strCopy = str[:-3] #removing the last + sign    return strCopy def getEgyptianFractionUtil(numerator,denominator,listOfDenoms):    if numerator == 0:        return listOfDenoms    newDenom = math.ceil(denominator/numerator);    #append in output list    listOfDenoms.append(newDenom);    listOfDenoms = getEgyptianFractionUtil(numerator*newDenom - denominator,                                          newDenom*denominator,listOfDenoms);    return listOfDenoms print(getEgyptianFraction(6,14))  # Code contributed by  # Mayur Sonowal
The Greedy algorithm works because a fraction is always reduced to a form where denominator is greater than numerator and numerator doesn’t divide denominator. For such reduced forms, the highlighted recursive call is made for reduced numerator. So the recursive calls keep on reducing the numerator till it reaches 1.  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Greedy Algorithm for Egyptian Fraction | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersGreedy Algorithm for Egyptian Fraction | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=8icU9XMEwjs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
References: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/egyptian.htmlThis article is contributed by Shubham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 
DhruvitJakasaniya
anubhavraj_08
Akanksha_Rai
Rajput-Ji
jit_t
divyeshrabadiya07
mayursonowal1997
Fraction
Greedy
Mathematical
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.