Lab 2: Big Fractions
Bard College – Computer Science – Data Structures

In this lab, we will create a new user-defined type for doing math on Rational numbers, or in other terms, adding, subtracting, multiplying, and dividing fractions. 

407409+409419+419421+421431=12261837304431095439321\frac{407}{409} + \frac{409}{419} + \frac{419}{421} + \frac{421}{431} = \frac{122618373044}{31095439321}

Rather than using int or  long as our underlying primitive datatype, we'll use BigInteger which is a little cumbersome, but allows exact arithmetic (i.e. no overflows).

> 123456 * 123456
-1938485248

> BigInteger.valueOf(123456).multiply(BigInteger.valueOf(123456))
1524138393

After all what good is a Fraction class that cannot add four simple fractions.

Fraction f1 = new Fraction(407, 409);
Fraction f2 = new Fraction(409, 419);
Fraction f3 = new Fraction(419, 421);
Fraction f4 = new Fraction(421, 431);
System.out.println(f1.add(f2).add(f3).add(f4));
645226180/-343556083

This is clearly a wrong answer. But BigInteger to the rescue.

System.out.println(f1.add(f2).add(f3).add(f4));
122618373044/31095439321

A Rational Datatype: Fraction

First, let's introduce the Fraction interface (that you should not change):

public class Fraction extends Number
    Fraction (BigInteger n, BigInteger d) throws IllegalArgumentException
    Fraction (BigInteger n) 
    Fraction (int n, int d)               throws IllegalArgumentException
    Fraction (int n)
    BigInteger getNumerator()
    BigInteger getDenominator()
    Fraction add(Fraction f)
    Fraction subtract(Fraction f)
    Fraction multiply(Fraction f)
    Fraction divide(Fraction f)
    boolean equals(Object o)
    String toString()
    static Fraction valueOf(int n, int d)
    double doubleValue()
    float floatValue()
    long longValue()
    int intValue()