From d093aeb1b99fbd269dd587f18113565455bc6790 Mon Sep 17 00:00:00 2001 From: shivu2806 <91802335+shivu2806@users.noreply.github.com> Date: Sun, 3 Oct 2021 01:31:44 +0530 Subject: [PATCH] Create egyptianFraction.java --- egyptianFraction.java | 56 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 egyptianFraction.java diff --git a/egyptianFraction.java b/egyptianFraction.java new file mode 100644 index 0000000..7a40f58 --- /dev/null +++ b/egyptianFraction.java @@ -0,0 +1,56 @@ +//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*/