Created
January 20, 2021 21:26
-
-
Save maxpushka/4e1500d8d41a933114d589a4080ca90b 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
int gcd(const int& n, const int& m) { | |
int a = n, b = m; | |
if (b > a) swap(a, b); | |
while (b) { | |
a = a % b; | |
swap(a, b); | |
} | |
return a; | |
} | |
int lcm(const int& n, const int& m) { return n / gcd(n, m) * m; } | |
class Rational { | |
public: | |
Rational(int numer, int denom) : n{numer}, d{denom} { | |
if (d == 0) throw ZeroDivError{}; | |
}; | |
Rational() : n{1}, d{1} {}; | |
int num() const { return n; } | |
int denom() const { return d; } | |
float dec() const { return (float)n / d; } | |
void simplify(); | |
private: | |
int n; // numerator | |
int d; // denominator | |
class ZeroDivError {}; // for exception generation | |
}; | |
void Rational::simplify() { | |
int gcd_value; | |
while (true) { | |
gcd_value = gcd(n, d); | |
if (gcd_value == 1) break; | |
n /= gcd_value; | |
d /= gcd_value; | |
} | |
} | |
ostream& operator<<(ostream& os, Rational& r) { | |
os << r.num() << '/' << r.denom(); | |
return os; | |
} | |
Rational operator+(const Rational& a, const Rational& b) { | |
int lcm_val = lcm(a.denom(), b.denom()); | |
int af1 = lcm_val / a.denom(); // additional factor | |
int af2 = lcm_val / b.denom(); | |
Rational res{ (a.num() * af1) + (b.num() * af2), lcm_val}; | |
res.simplify(); | |
return res; | |
} | |
Rational operator-(const Rational& a, const Rational& b) { | |
int lcm_val = lcm(a.denom(), b.denom()); | |
int af1 = lcm_val / a.denom(); // additional factor | |
int af2 = lcm_val / b.denom(); | |
Rational res{(a.num() * af1) - (b.num() * af2), lcm_val}; | |
res.simplify(); | |
return res; | |
} | |
Rational operator*(const Rational& a, const Rational& b) { | |
Rational res{a.num() * b.num(), a.denom() * b.denom()}; | |
res.simplify(); | |
return res; | |
} | |
Rational operator/(const Rational& a, const Rational& b) { | |
Rational temp{b.denom(), b.num()}; | |
return a*temp; | |
} | |
bool operator==(const Rational& a, const Rational& b) { | |
Rational _a = a, _b = b; | |
_a.simplify(); _b.simplify(); | |
return (_a.num() == _b.num()) && (_a.denom() == _b.denom()); | |
} | |
bool operator!=(const Rational& a, const Rational& b) { | |
return !(a == b); | |
} | |
bool operator>(const Rational& a, const Rational& b) { | |
return a.dec() > b.dec(); | |
} | |
bool operator<(const Rational& a, const Rational& b) { | |
return a.dec() < b.dec(); | |
} | |
bool operator>=(const Rational& a, const Rational& b) { | |
return a.dec() >= b.dec(); | |
} | |
bool operator<=(const Rational& a, const Rational& b) { | |
return a.dec() <= b.dec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment