Search code examples
javafractions

How to simplify a fraction when both nums are ints


I must simplify a fraction as much as possible. Must be Java.

This is what I have so far

if (numerator != 0)
    {

        numerator += denominator;
        denominator += numerator /2;
    }

Solution

  • I'll start off by saying that you need more practice with Java. Your code isn't even close...

    if (numerator != 0) 
        {
            int common = gcd(Math.abs(numerator), denominator); // Gets a common denominator and uses abs to  make sure it is positive.
            numerator = numerator / common; // Divides top number by common #
            denominator = denominator / common; // Divides bottom number by common #
        }
    

    You'll need to import java.util.Math; and you'll have to also get the GCD like i did. To get the GCD you say

    while (num1 != num2)
        {
            if (num1 > num2)
            {
                num1 = num1 - num2;
            }
            else
            {
                num2 = num2 - num1;
            }
        }
        return num1;
    

    I hope this makes sense to you. It's not too hard after you understand it. Let me know if you have any more questions!