Created
October 2, 2014 14:38
-
-
Save ekd123/137fa6fd064d7abeb27e to your computer and use it in GitHub Desktop.
a Rational class implementation which corresponds to Algs4 1.2.16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
plus and minus are just wrong. Please be careful.