Question

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;
    }
Was it helpful?

Solution 2

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!

OTHER TIPS

btw. the shortest possible gcd method is this.

static int gcd(int a, int b) {
    if(b == 0) return a;
    else return gcd(b, a%b);
}

it's also a lot faster than using subtraction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top