Bard College – Computer Science – Data Structures
In this lab, we will create a new user-defined type for doing arithmetic on Rational numbers, or 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
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()
int compareTo(Fraction f) --- optional