#include #include "Rational.h" bool Rational::gt(const Rational& other) const { // x a x*b a*y // - ? - <=> --- ? --- <=> x*b ? a*y // y b y*b y*b return numerator * other.denumerator > other.numerator * denumerator; } bool Rational::lt(const Rational& other) const { // x a x*b a*y // - ? - <=> --- ? --- <=> x*b ? a*y // y b y*b y*b return numerator * other.denumerator < other.numerator * denumerator; } int Rational::gcd() const { int a = numerator, b = denumerator; if (a < b) { int temp = a; a = b; b = temp; } while (b != 0) { int r = a % b; a = b; b = r; } return a; } Rational::Rational() : Rational(1, 1) {} Rational::Rational(int numerator, int denumerator) { if (denumerator == 0) numerator = denumerator = 1; set_numerator(numerator); set_denumerator(denumerator); } int Rational::get_numerator() const { return numerator; } void Rational::set_numerator(int numerator) { this->numerator = numerator; } int Rational::get_denumerator() const { return denumerator; } void Rational::set_denumerator(int denumerator) { if (denumerator == 0) denumerator = 1; this->denumerator = denumerator; } void Rational::canonize() { int gcdND = abs(gcd()); set_numerator(numerator / gcdND); set_denumerator(denumerator / gcdND); } // Not needed, kept for fun void Rational::canonizeRec() { if (denumerator == 1) return; int whole = numerator / denumerator, leftover = numerator % denumerator; if (leftover == 0) { numerator = whole; denumerator = 1; return; } Rational temp(denumerator, leftover); temp.canonize(); numerator = whole * temp.numerator + temp.denumerator; denumerator = temp.numerator; } Rational Rational::operator+(const Rational& other) const { // x a x*b + a*y // - + - = --------- // y b y*b return Rational(numerator * other.denumerator + other.numerator * denumerator, denumerator * other.denumerator); } Rational Rational::operator-(const Rational& other) const { // x a x*b - a*y // - - - = --------- // y b y*b return Rational(numerator * other.denumerator - other.numerator * denumerator, denumerator * other.denumerator); } Rational Rational::operator*(const Rational& other) const { // x a x*b // - / - <=> --- // y b y*a return Rational(numerator * other.numerator, denumerator * other.denumerator); } Rational Rational::operator/(const Rational& other) const { // x a x b // - / - <=> - * - // y b y a return Rational(numerator * other.denumerator, denumerator * other.numerator); } int Rational::numcmp(const Rational& arg) const { return gt(arg) - lt(arg); } void Rational::print() const { std::cout << numerator << "/" << denumerator; }