Rational.java
Below is the syntax highlighted version of Rational.java
from §3.2 Creating Data Types.
/*************************************************************************
* Compilation: javac Rational.java
* Execution: java Rational
*
* ADT for nonnegative Rational numbers. Bare-bones implementation.
* Cancel common factors, but does not stave off overflow. Does not
* support negative fractions or zero.
*
* Invariant: all Rational objects are in reduced form (except
* possibly while modifying).
*
*************************************************************************/
public class Rational {
private int num; // the numerator
private int den; // the denominator
// create and initialize a new Rational object
public Rational(int numerator, int denominator) {
int g = gcd(numerator, denominator);
num = numerator / g;
den = denominator / g;
}
// return string representation of (this)
public String toString() {
if (den == 1) return num + "";
else return num + "/" + den;
}
// return a * b
public Rational times(Rational b) {
Rational a = this;
return new Rational(a.num * b.num, a.den * b.den);
}
// return a + b
public Rational plus(Rational b) {
Rational a = this;
int numerator = (a.num * b.den) + (a.den * b.num);
int denominator = a.den * b.den;
return new Rational(numerator, denominator);
}
// return 1 / a
public Rational reciprocal() { return new Rational(den, num); }
// return a / b
public Rational divides(Rational b) {
Rational a = this;
return a.times(b.reciprocal());
}
/*************************************************************************
* Helper functions
*************************************************************************/
// return gcd(m, n)
private static int gcd(int m, int n) {
if (0 == n) return m;
else return gcd(n, m % n);
}
// return lcm(m, n)
private static int lcm(int m, int n) {
return m * (n / gcd(m, n));
}
/*************************************************************************
* Test client
*************************************************************************/
public static void main(String[] args) {
Rational x, y, z;
// 1/2 + 1/3 = 5/6
x = new Rational(1, 2);
y = new Rational(1, 3);
z = x.plus(y);
System.out.println(z);
// 8/9 + 1/9 = 1
x = new Rational(8, 9);
y = new Rational(1, 9);
z = x.plus(y);
System.out.println(z);
// 4/17 * 7/3 = 128/51
x = new Rational(4, 17);
y = new Rational(7, 3);
z = x.times(y);
System.out.println(z);
// 203/16957 * 9299/5887 = 17/899
x = new Rational( 203, 16957);
y = new Rational(9299, 5887);
z = x.times(y);
System.out.println(z);
}
}
Last updated: Mon Oct 18 11:29:02 EDT 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.