Skip to content

Instantly share code, notes, and snippets.

@tomilov
Last active October 25, 2016 08:13
Show Gist options
  • Save tomilov/a10f0ea3dc248c4c31853366303fb340 to your computer and use it in GitHub Desktop.
Save tomilov/a10f0ea3dc248c4c31853366303fb340 to your computer and use it in GitHub Desktop.
#include <numeric>
#include <cassert>
class ratio
{
std::size_t n, d; // numerator, denominator
void
assign(std::size_t nn, std::size_t dd)
{
std::size_t gcd = std::gcd(nn, dd);
n = nn / gcd;
d = dd / gcd;
}
public :
ratio(std::size_t nn, std::size_t dd = 1)
: n(nn), d(dd)
{ ; }
ratio & operator = (std::size_t r) { n = r; d = 1; return *this; }
ratio & operator += (ratio const & r) { assign(n * r.d + r.n * d, d * r.d); return *this; }
ratio & operator -= (ratio const & r) { assert(!(n * r.d < r.n * d)); assign(n * r.d - r.n * d, d * r.d); return *this; }
ratio & operator *= (ratio const & r) { assign(n * r.n, d * r.d); return *this; }
ratio & operator /= (ratio const & r) { assign(n * r.d, d * r.n); return *this; }
friend ratio operator + (ratio l, ratio const & r) { return l += r; }
friend ratio operator - (ratio l, ratio const & r) { return l -= r; }
friend ratio operator * (ratio l, ratio const & r) { return l *= r; }
friend ratio operator / (ratio l, ratio const & r) { return l /= r; }
ratio & operator += (std::size_t r) { assign(n * r, d); return *this; }
ratio & operator -= (std::size_t r) { assign(n, d * r); return *this; }
ratio & operator *= (std::size_t r) { assign(n * r, d); return *this; }
ratio & operator /= (std::size_t r) { assign(n, d * r); return *this; }
friend ratio operator + (ratio l, std::size_t r) { return l += r; }
friend ratio operator - (ratio l, std::size_t r) { return l -= r; }
friend ratio operator * (ratio l, std::size_t r) { return l *= r; }
friend ratio operator / (ratio l, std::size_t r) { return l /= r; }
bool operator == (ratio const & r) const { return (n == r.n) && (d == r.d); }
bool operator < (ratio const & r) const { return n * r.d < r.n * d; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment