Skip to content
Advertisement

How would I make a new fraction if a fraction cannot be simplified?

So I’m writing an assignment for my OOP class that asks the user for a number of fractions, then randomly generates that number of fractions. Part of the assignment states that if one of the fractions cannot be simplified then skip it and create a new fraction that can be simplified. However the unreducible fractions still make it through. I need a way to have the program make a new fraction if the GCD of a fraction is 1.

Code:

JavaScript

Fraction Class code

JavaScript

}

JavaScript

Advertisement

Answer

  • Method decimal() in class Fraction is not used, so I removed it.
  • Rather than recursively call method getAGoodFraction() when the GCD value is 1, use a loop.
  • Rather than create a new Fraction object each time the randomly generated numerator is greater than the randomly generated denominator, use methods setNumerator() and setDenominator(). That’s what they’re for.
  • There is no need to call method simplify() in method getAGoodFraction(). Just return the fraction. Because the GCD is not equal to 1, you know it can be simplified.

Compare the following code with yours.
Note that I added a main() method to class Fraction so as to be able to run the code. And I also changed method gcd() due to the comment to your question from @KevinAnderson.

JavaScript

Here is a sample output produced when running the above code.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement