-
Notifications
You must be signed in to change notification settings - Fork 0
/
rational.cpp
85 lines (68 loc) · 2.88 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
#include <cmath>
#include <iostream>
#include <numeric>
class Rational {
private:
int numerator_, denominator_;
public:
Rational(int numerator = 0, int denominator = 1)
: numerator_(numerator)
, denominator_(denominator) {
int g = std::gcd(numerator_, denominator_);
numerator_ /= g;
denominator_ /= g;
if (denominator_ < 0) {
numerator_ = -numerator_;
denominator_ = -denominator_;
}
}
int numerator() const noexcept { return numerator_; }
int denominator() const noexcept { return denominator_; }
operator double() const {
return static_cast<double>(numerator()) / denominator();
}
Rational operator+() const { return *this; }
Rational operator-() const { return {-numerator(), denominator()}; }
Rational operator+(const Rational& o) const {
return {numerator() * o.denominator() + denominator() * o.numerator(),
denominator() * o.denominator()};
}
Rational operator-(const Rational& o) const { return (*this) + (-o); }
Rational operator*(const Rational& o) const {
return {numerator() * o.numerator(), denominator() * o.denominator()};
}
Rational operator/(const Rational& o) const {
return {numerator() * o.denominator(), denominator() * o.numerator()};
}
Rational operator+(int o) const { return (*this) + Rational(o); }
Rational operator-(int o) const { return (*this) - Rational(o); }
Rational operator*(int o) const { return (*this) * Rational(o); }
Rational operator/(int o) const { return (*this) / Rational(o); }
Rational& operator+=(const Rational& o) { return (*this) = (*this) + o; }
Rational& operator-=(const Rational& o) { return (*this) = (*this) - o; }
Rational& operator*=(const Rational& o) { return (*this) = (*this) * o; }
Rational& operator/=(const Rational& o) { return (*this) = (*this) / o; }
bool operator==(const Rational& o) const {
return numerator() * o.denominator() == o.numerator() * denominator();
}
bool operator!=(const Rational& o) const { return !(*this == o); }
Rational& operator++() { return (*this) += Rational(1, 1); }
Rational& operator--() { return (*this) -= Rational(1, 1); }
Rational operator++(int) {
Rational tmp = *this;
operator++();
return tmp;
}
Rational operator--(int) {
Rational tmp = *this;
operator--();
return tmp;
}
friend std::ostream& operator<<(std::ostream& os, const Rational& r) {
return os << r.numerator() << "/" << r.denominator();
}
};
Rational operator+(int o, const Rational& c) { return Rational(o) + c; }
Rational operator-(int o, const Rational& c) { return Rational(o) - c; }
Rational operator*(int o, const Rational& c) { return Rational(o) * c; }
Rational operator/(int o, const Rational& c) { return Rational(o) / c; }