// Implementation of Fraction Class, watching out for integer overflows.. // Michael Rothstein // 07/27/2014 // For many reasons, keep fractions in lowest terms #include "Fraction.h" #include #include Fraction::Fraction(long numerator,long denominator){ /* if ( denominator == 0 ) { cerr << "0 Denominators are not allowed!\n"; exit(1); }*/ assert(denominator != 0); if ( numerator == 0 ) denominator = 1; if ( denominator < 0 ) { numerator = -numerator; denominator = -denominator; } long g = gcd(numerator, denominator); numer = numerator/g; denom = denominator/g; } Fraction Fraction::operator+(const Fraction & a){ long g = gcd(denom,a.denom); long c1 = denom/g; long c2 = a.denom/g; long newnum = numer*c2+a.numer*c1; long newdenom = denom * c2; // = a.denom * c1 return Fraction(newnum,newdenom); } Fraction Fraction::operator-(const Fraction & a){ long g = gcd(denom,a.denom); long c1 = denom/g; long c2 = a.denom/g; long newnum = numer*c2-a.numer*c1; long newdenom = denom * c2; // = a.denom * c1 return Fraction(newnum,newdenom); } Fraction Fraction::operator*(const Fraction & a){ long g1 = gcd(numer,a.denom); long g2 = gcd(denom,a.numer); return Fraction((numer/g1)*(a.numer/g2),(denom/g2)*(a.denom/g1)); } Fraction Fraction::operator/(const Fraction & a){ long g1 = gcd(numer,a.numer); long g2 = gcd(denom,a.denom); return Fraction((numer/g1)*(a.denom/g2),(denom/g2)*(a.numer/g1)); } std::ostream& operator<<(std::ostream&os,const Fraction a){ if ( a.denom == 1 ) os << a.numer; else os << a.numer << '/'<< a.denom; return os; }