Loading...
Loading...
A maths worksheet app adds fractions. Every fraction it stores must be in lowest terms with a positive denominator: 6/-8 is kept as -3/4, and 4/2 as 2.
Write a class Fraction with fields num and den. The constructor Fraction(long num, long den) fixes the sign and divides by the GCD; Fraction(long whole) calls it with a denominator of 1. Add Fraction plus(Fraction other), which returns a new Fraction, and String text().
a/b or a whole number a.SUM s. A fraction whose denominator is 1 is printed as a whole number.Example
Input
3 1/2 2/6 5
Output
1/2 1/3 5 SUM 35/6
1/2 + 1/3 = 5/6, and 5/6 + 5 = 35/6.
Try the problem first. Open one hint at a time.
If den is negative, flip the signs of both before reducing.
GCD with Euclid: keep replacing (a, b) with (b, a % b) until b is 0. Use Math.abs(num).
a/b + c/d = (ad + cb) / bd; build the answer with new Fraction(...) so it is reduced automatically.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor