Egyptian fraction solution in java

Java program for Egyptian fraction solution. Here problem description and explanation.

/*
  Java program for
  Egyptian fraction solution
*/
public class Fraction
{
    public void egyptianFraction(int a, int b)
    {
        if (a == 0 || b == 0)
        {
            return;
        }
        if (b >= a)
        {
            // Calculate remainder
            int remainder = b % a;
            // Calculate divisor
            int divisor = b / a;
            if (remainder != 0)
            {
                divisor++;
                System.out.print("1/" + divisor + " + ");
                a = a * divisor - b;
                b = b * divisor;
                egyptianFraction(a, b);
            }
            else
            {
                // When remainder is zero
                System.out.print("1/" + divisor);
            }
        }
        else
        {
          	// When b < a
            System.out.print((a / b) + " + ");
            egyptianFraction(a % b, b);
        }
    }
    public static void main(String[] args)
    {
        Fraction task = new Fraction();
        // Two numbers
        int a = 7;
        int b = 53;
        task.egyptianFraction(a, b);
    }
}

Output

1/8 + 1/142 + 1/30104


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved