|
| 1 | +#include <bits/stdc++.h> |
| 2 | + |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +template<class T> |
| 6 | +struct rational { |
| 7 | + T a, b; |
| 8 | + |
| 9 | + rational(T a, T b = 1) : a{a}, b{b} { |
| 10 | + normalize(); |
| 11 | + } |
| 12 | + |
| 13 | + void normalize() { |
| 14 | + if (b < 0) { |
| 15 | + a = -a; |
| 16 | + b = -b; |
| 17 | + } |
| 18 | + auto g = gcd(::abs(a), b); |
| 19 | + if (g != 0) { |
| 20 | + a /= g; |
| 21 | + b /= g; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + bool operator==(rational rhs) const { return a == rhs.a && b == rhs.b; } |
| 26 | + |
| 27 | + bool operator!=(rational rhs) const { return !(*this == rhs); } |
| 28 | + |
| 29 | + bool operator<(rational rhs) const { return a * rhs.b < b * rhs.a; } |
| 30 | + |
| 31 | + bool operator<=(rational rhs) const { return !(rhs < *this); } |
| 32 | + |
| 33 | + bool operator>(rational rhs) const { return rhs < *this; } |
| 34 | + |
| 35 | + bool operator>=(rational rhs) const { return !(*this < rhs); } |
| 36 | + |
| 37 | + rational operator-() const { return rational(-a, b); } |
| 38 | + |
| 39 | + rational abs() const { return rational(::abs(a), b); } |
| 40 | + |
| 41 | + rational &operator+=(rational rhs) { |
| 42 | + a = a * rhs.b + b * rhs.a; |
| 43 | + b *= rhs.b; |
| 44 | + normalize(); |
| 45 | + return *this; |
| 46 | + } |
| 47 | + |
| 48 | + rational &operator-=(rational rhs) { |
| 49 | + a = a * rhs.b - b * rhs.a; |
| 50 | + b *= rhs.b; |
| 51 | + normalize(); |
| 52 | + return *this; |
| 53 | + } |
| 54 | + |
| 55 | + rational &operator*=(rational rhs) { |
| 56 | + a *= rhs.a; |
| 57 | + b *= rhs.b; |
| 58 | + normalize(); |
| 59 | + return *this; |
| 60 | + } |
| 61 | + |
| 62 | + rational &operator/=(rational rhs) { |
| 63 | + a *= rhs.b; |
| 64 | + b *= rhs.a; |
| 65 | + normalize(); |
| 66 | + return *this; |
| 67 | + } |
| 68 | + |
| 69 | + friend rational operator+(rational lhs, rational rhs) { return lhs += rhs; } |
| 70 | + |
| 71 | + friend rational operator-(rational lhs, rational rhs) { return lhs -= rhs; } |
| 72 | + |
| 73 | + friend rational operator*(rational lhs, rational rhs) { return lhs *= rhs; } |
| 74 | + |
| 75 | + friend rational operator/(rational lhs, rational rhs) { return lhs /= rhs; } |
| 76 | +}; |
0 commit comments