Rational Arithmetic

 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
function Rational(numerator, denominator) {
this.numerator = numerator;
this.denominator = denominator || 1;
this.simplify();
};
function GCD(a,b) {
var t = 0;
while(b != 0) {
t=b
b = a % b
a = t
}
return a
}
Rational.prototype.toString = function () {
return this.numerator + "/" + this.denominator;
};
Rational.prototype.simplify = function () {
var sign = this.numerator*this.denominator <= 0 ? -1 : 1;
this.numerator = Math.abs(this.numerator);
this.denominator = Math.abs(this.denominator);
var divisor = GCD(this.numerator,this.denominator);
this.numerator = sign*this.numerator/divisor;
this.denominator = this.denominator/divisor;
};
Rational.prototype.equals = function (b) {
return this.numerator == b.numerator && this.denominator == b.denominator;
};
Rational.prototype.lessThan = function (b) {
return this.numerator*b.denominator < b.numerator*this.denominator;
};
Rational.prototype.greaterThan = function (b) {
return this.numerator*b.denominator > b.numerator*this.denominator;
};
Rational.prototype.lessThanOrEquals = function (b) {
return this.numerator*b.denominator <= b.numerator*this.denominator;
};
Rational.prototype.greaterThanOrEquals = function (b) {
return this.numerator*b.denominator >= b.numerator*this.denominator;
};
Rational.prototype.add = function (b) {
return new Rational(this.numerator*b.denominator+ b.numerator*this.denominator,
b.denominator*this.denominator);
};
Rational.prototype.sub = function (b) {
return new Rational(this.numerator*b.denominator - b.numerator*this.denominator,
b.denominator*this.denominator);
};
Rational.prototype.mul = function (b) {
return new Rational(this.numerator*b.numerator,b.denominator*this.denominator);
};
Rational.prototype.div = function (b) {
return new Rational(this.numerator*b.denominator, b.numerator*this.denominator);
};