Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Rational {
- // the rational number a/b
- private final long a;
- private final long b;
- public Rational(long a, long b) {
- this.a = a;
- this.b = b;
- }
- public Rational(int a, int b) {
- this.a = a;
- this.b = b;
- }
- private static Rational lowestForm(long a, long b) {
- long x = a;
- long y = b;
- while (b != 0) {
- long t = b;
- b = a % b;
- a = t;
- }
- return new Rational(x / a, y / a);
- }
- public String toString() {
- return a + "/" + b;
- }
- public Rational add(Rational other) {
- return lowestForm(a * other.b + b * other.a, b * other.b);
- }
- public Rational div(Rational other) {
- return lowestForm(a * other.b, b * other.a);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment