1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| class Rational{ private final long numerator; private final long denominator; public Rational(long numerator, long denominator){ if (denominator == 0){ throw new RuntimeException("Denominator is zero"); } long f = euclidean(numerator, denominator); this.numerator = numerator / f; this.denominator = denominator / f; } private long euclidean(long a, long b){ if (a == 0) return 1; if (a < 0) a = -a; if (b < 0) b = -b; if (a < b){ long d = a; a = b; b = d; } long c = a % b; if (c != 0){ return euclidean(b, c); } else { return b; } } public Rational plus(Rational b){ long u = numerator * b.denominator + denominator * b.numerator; long d = denominator * b.denominator; return new Rational(u, d); } public Rational minus(Rational b){ long u = numerator * b.denominator - denominator * b.numerator; long d = denominator * b.denominator; return new Rational(u, d); } public Rational times(Rational b){ return new Rational(numerator * b.numerator, denominator * b.denominator); } public Rational divides(Rational b){ return new Rational(numerator * b.denominator, denominator * b.numerator); } public boolean equals(Rational b){ if (this == b) return true; if (b == null) return false; return (numerator == b.numerator && denominator == b.denominator); } public String toString(){ if (this.denominator == 1){ return String.format("%d", this.numerator); } return String.format("%d/%d", this.numerator, this.denominator); } } public class q1216{ public static void main(String[] args){ System.out.println(6/ -3); Rational r = new Rational(2, -6); System.out.println(r); Rational r1 = new Rational(1, 5); Rational r2 = new Rational(-1, 15); System.out.println(r.plus(r1)); System.out.println(r.plus(r2).plus(r1)); System.out.println(r.minus(r1)); System.out.println(r.times(r1)); System.out.println(r.divides(r1)); System.out.println(r.times(r1).equals(r2)); r = new Rational(0, 2); System.out.println(r); System.out.println(r.plus(r1)); r1 = new Rational(1, 3); r2 = new Rational(2, 3); System.out.println(r1.plus(r2)); r1 = new Rational(1, 200000000); r2 = new Rational(1, 300000000); System.out.println(r1.plus(r2)); r1 = new Rational(1073741789, 20); r2 = new Rational(1073741789, 30); System.out.println(r1.plus(r2)); } }
|