Bard College – Computer Science – Data Structures
In this lab, we will create a new user-defined type for doing arithmetic on Rational numbers, or put in other terms: adding, subtracting, multiplying, and dividing fractions.
Rather than using int or long as our underlying primitive data type, we'll use BigInteger which is a little cumbersome, but allows exact arithmetic(i.e. no overflows).
jshell> 123456 * 123456
-1938485248
jshell> BigInteger.valueOf(123456).multiply(BigInteger.valueOf(123456))
1524138393
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
System.out.println(f1.add(f2).add(f3).add(f4));
122618373044/31095439321
A Rational Datatype: Fraction
public class Fraction extends Number
Fraction (BigInteger n, BigInteger d) throws IllegalArgumentException
// creates a new fraction with the numerator n and denominator d
// throw an exception if the denominator is zero
Fraction (BigInteger n)
// creates a new fraction with the numerator n and denominator 1
Fraction (int n, int d) throws IllegalArgumentException
// creates a new fraction with the numerator n and denominator d
// throw an exception if the denominator is zero
Fraction (int n)
// creates a new fraction with the numerator n and denominator 1
BigInteger getNumerator()
// returns the numerator