-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrational.cpp
98 lines (82 loc) · 2.25 KB
/
rational.cpp
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
94
95
96
97
/**
* File: rational.cpp
* ------------------
* Created by Jerry Cain on 5/9/09.
*/
#include "genlib.h"
#include "rational.h"
#include "strutils.h"
RationalExpression::RationalExpression(int numerator, int denominator) {
this->numerator = numerator;
this->denominator = denominator;
reduce();
}
RationalExpression::RationalExpression(Scanner& s) {
this->numerator = StringToInteger(s.nextToken());
string lookahead = s.nextToken();
if (lookahead == "/") {
this->denominator = StringToInteger(s.nextToken());
} else {
s.saveToken(lookahead);
this->denominator = 1;
}
reduce();
}
string RationalExpression::toString() {
string stringRep = IntegerToString(numerator);
if (denominator > 1) {
stringRep += '/';
stringRep += IntegerToString(denominator);
}
return stringRep;
}
RationalExpression *RationalExpression::add(RationalExpression *other) {
int numerator =
this->numerator * other->denominator +
this->denominator * other->numerator;
int denominator =
this->denominator * other->denominator;
return new RationalExpression(numerator, denominator);
}
RationalExpression *RationalExpression::subtract(RationalExpression *other) {
int numerator =
this->numerator * other->denominator -
this->denominator * other->numerator;
int denominator =
this->denominator * other->denominator;
return new RationalExpression(numerator, denominator);
}
RationalExpression *RationalExpression::multiply(RationalExpression *other) {
return new RationalExpression(this->numerator * other->numerator,
this->denominator * other->denominator);
}
bool RationalExpression::equals(RationalExpression *other) {
return
this->numerator * other->denominator ==
this->denominator * other->numerator;
}
bool RationalExpression::lessThan(RationalExpression *other) {
return
this->numerator * other->denominator <
this->denominator * other->numerator;
}
void RationalExpression::reduce() {
int divisor = gcd(abs(numerator),
abs(denominator));
numerator /= divisor;
denominator /= divisor;
if (denominator < 0) {
numerator *= -1;
denominator *= -1;
}
}
int RationalExpression::gcd(int a, int b) {
if (a < b) swap(a, b);
while (b > 0) {
// gcd(a, b) == gcd(b, a % b);
int old = a;
a = b;
b = old % b;
}
return a;
}