-
Notifications
You must be signed in to change notification settings - Fork 0
/
fraction_data_type.cpp
61 lines (56 loc) · 1.46 KB
/
fraction_data_type.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
#define ll long long
struct Fraction {
ll n, d; // represent n/d
Fraction(ll N, ll D) { n = N, d = D; reduce(); }
Fraction(ll N) { n = N, d = 1; }
Fraction() { n = 0, d = 1; }
ll gcd(ll a, ll b) {
if (b == 0) return a;
else return gcd(b, a % b);
}
void reduce() {
//ll g = gcd(n, d);
//n /= g, d /= g;
if (d < 0) n *= -1, d *= -1;
}
bool operator==(const Fraction& rhs) const {
return n * rhs.d == rhs.n * d;
}
bool operator!=(const Fraction& rhs) const {
return n * rhs.d != rhs.n * d;
}
bool operator<(const Fraction& rhs) const {
return n * rhs.d < rhs.n * d;
}
bool operator>(const Fraction& rhs) const {
return n * rhs.d > rhs.n * d;
}
Fraction operator+(const Fraction& rhs) const {
Fraction ret;
ret.n = n * rhs.d + rhs.n * d;
ret.d = d * rhs.d;
ret.reduce();
return ret;
}
Fraction operator-(const Fraction& rhs) const {
Fraction ret;
ret.n = n * rhs.d - rhs.n * d;
ret.d = d * rhs.d;
ret.reduce();
return ret;
}
Fraction operator*(const Fraction& rhs) {
Fraction ret;
ret.n = n * rhs.n;
ret.d = d * rhs.d;
ret.reduce();
return ret;
}
Fraction operator/(const Fraction& rhs) {
Fraction ret;
ret.n = n * rhs.d;
ret.d = d * rhs.n;
ret.reduce();
return ret;
}
};