1 /**
2 * The Rational class is used to represent rational numbers, which3 * are defined to be the quotient of two integer.4 *@authorAdministrator5 *6 */
7 public classRational {8 /**Creates a new Rational from the integer argument.*/
9 publicRational(){10 this(0);11 }12
13 /**
14 * Creates a new Rational from the integer argument.15 *@paramn The initial value16 */
17 public Rational(intn){18 this(n,1);19 }20
21 /**
22 * Creates a new Rational with the value x / y.23 *@paramx The numerator of the rational number24 *@paramy The denominator of the rational number25 */
26 public Rational(int x, inty) {27 int g =gcd(Math.abs(x), Math.abs(y));28 num = x /g;29 den = Math.abs(y) /g;30 if(y < 0) num = -num;31 }32
33 /**
34 * Adds the rational number r to this one and returns the sum.35 *@paramr The rational number to be added36 *@returnThe sum of the current number and r37 */
38 publicRational add(Rational r) {39 return new Rational(this.num * r.den + r.num * this.den, this.den *r.den);40 }41
42 /**
43 * Subtracts the rational number r from this one.44 *@paramr The rational number to be subtracted45 *@returnThe result of subtracting r from the current number46 */
47 publicRational substract(Rational r) {48 return new Rational(this.num * r.den - r.num * this.den, this.den *r.den);49 }50
51 /**
52 * Multiplies this number by the rational number r.53 *@paramr The rational number used as a multiplier54 *@returnThe result of multiplying the current number by r55 */
56 publicRational multiply(Rational r) {57 return new Rational(this.num * r.num, this.den *r.den);58 }59
60 /**
61 * Divides this number by the rational number r.62 *@paramr The rational number used as a divisor63 *@returnThe result of dividing the current number by r64 */
65
66 publicRational divide(Rational r){67 return new Rational(this.num * r.den, this.den *r.num);68 }69
70 /**
71 * Creates a string representation of this rational number.72 *@returnThe string representation of this rational number73 */
74 publicString toString() {75 if (den == 1) {76 return "" +num;77 } else{78 return num + "/" +den;79 }80 }81
82 /**
83 * Calculates the greatest common divisor using Euclid's algorithm.84 *@paramx First integer85 *@paramy Second integer86 *@returnThe greatest common divisor of x and y87 */
88 public int gcd (int x, inty) {89 int r = x %y;90 while (r != 0) {91 x =y;92 y =r;93 r = x %y;94 }95 returny;96 }97 /*Private instance variables*/
98 private int num; /*The numerator of this Rational*/
99 private int den; /*The denominator of this Rational*/
100 }