Skip to content

Instantly share code, notes, and snippets.

@alecGraves
Last active August 24, 2017 15:27
Show Gist options
  • Save alecGraves/9444d56ba49da1ea73b4ea8c07c81f1d to your computer and use it in GitHub Desktop.
Save alecGraves/9444d56ba49da1ea73b4ea8c07c81f1d to your computer and use it in GitHub Desktop.
Tiny Rational Class MTRE 2610
#include <cstdio>
class Rational{
int n, d; //numerator, denominator
int gcf(int x, int y, int z){ return y&&(z=x%y) ? gcf(y,z,0) : y;}
void r(){int f=gcf(n, d, 0); n/=f; d/=f;} //reduce
public:
Rational operator+(Rational R){return Rational(n*R.d+d*R.n, d*R.d);}
Rational operator-(Rational R){return Rational(n*R.d-d*R.n, d*R.d);}
Rational operator*(Rational R){return Rational(n*R.n, d*R.d);}
Rational operator/(Rational R){return Rational(n*R.d, d*R.n);}
Rational operator+(int i){return Rational(n+d*i, d);}
Rational operator-(int i){return Rational(n-d*i, d);}
Rational operator*(int i){return Rational(n*i, d);}
Rational operator/(int i){return Rational(n, d*i);}
int getNumer(){return n;}
int getDenom(){return d;}
void print(){printf("%d/%d\n", n, d);}
Rational() :n(0),d(1) {}
Rational(int N, int D) :n(N), d(D) {}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment