-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmath-ratio.cpp
More file actions
64 lines (49 loc) · 1.36 KB
/
math-ratio.cpp
File metadata and controls
64 lines (49 loc) · 1.36 KB
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
template<class IntegerType>
struct TRatio {
IntegerType up, down;
explicit TRatio(IntegerType u) : up(u), down(1) {}
TRatio(IntegerType u, IntegerType d) {
assert(d != 0);
const IntegerType g = gcd(u, d);
up = u / g;
down = d / g;
if (down < 0) {
up *= -1;
down *= -1;
}
}
IntegerType gcd(IntegerType a, IntegerType b) {
a = abs(a);
b = abs(b);
while (b) {
a %= b;
swap(a, b);
}
return a;
}
TRatio operator*(int64_t value) const {
return TRatio(up * value, down);
}
TRatio operator+(const TRatio& other) const {
return TRatio(up * other.down + other.up * down, down * other.down);
}
TRatio operator-(const TRatio& other) const {
return TRatio(up * other.down - other.up * down, down * other.down);
}
TRatio operator*(const TRatio& other) const {
return TRatio(up * other.up, down * other.down);
}
TRatio operator/(const TRatio& other) const {
return TRatio(up * other.down, down * other.up);
}
bool operator<(const TRatio& other) const {
return up * other.down < other.up* down;
}
bool operator<=(const TRatio& other) const {
return up * other.down <= other.up * down;
}
};
template<class T>
ostream& operator<<(ostream& os, const TRatio<T>& ratio) {
return os << ratio.up << "/" << ratio.down << "~(" << double(ratio.up) / ratio.down << ")";
}