Skip to content

Instantly share code, notes, and snippets.

@ekd123
Created October 2, 2014 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekd123/137fa6fd064d7abeb27e to your computer and use it in GitHub Desktop.
Save ekd123/137fa6fd064d7abeb27e to your computer and use it in GitHub Desktop.
a Rational class implementation which corresponds to Algs4 1.2.16
public class Rational {
private long n;
private long d;
public Rational (long numerator, long denominator) {
n = numerator;
d = denominator;
}
public long gcd(long p, long q) {
if (q == 0) return p;
long r = p % q;
return gcd(q, r);
}
private void simplify() {
long r = gcd(n, d);
n = n / r;
d = d / r;
}
public Rational plus(Rational b) {
Rational result = new Rational(n, d);
result.n = result.n + b.n;
result.simplify();
return result;
}
public Rational minus(Rational b) {
Rational result = new Rational(n, d);
result.n = result.n - b.n;
result.simplify();
return result;
}
public Rational times(Rational b) {
Rational result = new Rational(n, d);
result.n = result.n * b.n;
result.d = result.d * b.d;
result.simplify();
return result;
}
// a / b, not b / a
public Rational divides(Rational b) {
Rational result = new Rational(n, d);
result.n = result.n * b.d;
result.d = result.d * b.n;
result.simplify();
return result;
}
public boolean equals(Rational b) {
if (b.n == n && b.d == d) {
return true;
} else {
return false;
}
}
public String toString() {
if (d == 1 || d == 0) {
return String.format("%d", n);
} else {
return String.format("%d/%d", n, d);
}
}
public static void main(String[] args) {
Rational a = new Rational(3, 4);
Rational b = new Rational(1, 4);
StdOut.println(a.plus(b));
StdOut.println(a.minus(b));
StdOut.println(a.times(b));
StdOut.println(a.divides(b));
StdOut.println(a.minus(b).equals(a.minus(b)));
}
}
@ekd123
Copy link
Author

ekd123 commented Oct 3, 2014

plus and minus are just wrong. Please be careful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment