Last active
March 29, 2023 19:56
-
-
Save warm-ice0x00/e7aaaada4baa7415d52e6d6f69af6fd8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
template <class T> | |
class Rational { | |
public: | |
Rational(T a, T b) : p(a), q(b) { | |
if (b == 0) throw std::domain_error("ZeroDivisionError"); | |
while (b) { | |
T t = b; | |
b = a % b; | |
a = t; | |
} | |
p /= a, q /= a; | |
if (q < 0) p = -p, q = -q; | |
} | |
Rational operator+(const Rational& r) const { | |
return Rational(p * r.q + r.p * q, q * r.q); | |
} | |
Rational operator-(const Rational& r) const { | |
return *this + Rational(-r.p, r.q); | |
} | |
Rational operator*(const Rational& r) const { | |
return Rational(p * r.p, q * r.q); | |
} | |
Rational operator/(const Rational& r) const { | |
return *this * Rational(r.q, r.p); | |
} | |
bool operator==(const Rational& r) const { return p * r.q == r.p * q; } | |
bool operator!=(const Rational& r) const { return !(*this == r); } | |
bool operator<(const Rational& r) const { return p * r.q < r.p * q; } | |
bool operator>(const Rational& r) const { return r < *this; } | |
bool operator<=(const Rational& r) const { return !(*this > r); } | |
bool operator>=(const Rational& r) const { return !(*this < r); } | |
T get_num() const { return p; } | |
T get_den() const { return q; } | |
friend std::ostream& operator<<(std::ostream& os, const Rational& r) { | |
os << r.p; | |
if (r.q != 1) os << '/' << r.q; | |
return os; | |
} | |
private: | |
T p, q; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment