#ifndef ARRAY_H #define ARRAY_H #include template struct Fraction { Integer numerator; // fields -> attributes Integer denominator; // member = attributes | method }; template const Integer& gcd(const Integer& a, const Integer& b) { // TODO(any): verify behvaior with a or b negatives if (b == 0) { return a; } else { return gcd(b, a % b); } } template void fraction_simplify(Fraction* fraction) { assert(fraction); const Integer& fraction_gcd = gcd(fraction->numerator, fraction->denominator); fraction->numerator /= fraction_gcd; fraction->denominator /= fraction_gcd; if (fraction->denominator < 0) { fraction->numerator = -fraction->numerator; fraction->denominator = -fraction->denominator; } } template void fraction_init(Fraction* fraction, const Integer& numerator = 0, const Integer& denominator = 1) { // default arguments assert(fraction); fraction->numerator = numerator; fraction->denominator = denominator; fraction->fraction_simplify(); } template std::ostream& fraction_print(std::ostream& output , const Fraction& fraction) { return output << fraction.numerator << '/' << fraction.denominator; } template std::ostream& operator<<(std::ostream& output , const Fraction& fraction) { return output << fraction.numerator << '/' << fraction.denominator; } template std::istream& operator>>(std::istream& input, Fraction& fraction) { input >> fraction.numerator >> fraction.denominator; // fraction_simplify(&fraction); fraction.fraction_simplify(); return input; } template Fraction add(const Fraction& fr1 , const Fraction& fr2) { Fraction result; // a/b + c/d = (ad + bc)/(bd) result.numerator = fr1.numerator * fr2.denominator + fr1.denominator * fr2.numerator; result.denominator = fr1.denominator * fr2.denominator; // fraction_simplify(&result); result.fraction_simplify(); return result; } template Fraction operator+(const Fraction& fr1 , const Fraction& fr2) { Fraction result; // a/b + c/d = (ad + bc)/(bd) fraction_init(&result , fr1.numerator * fr2.denominator + fr1.denominator * fr2.numerator , fr1.denominator * fr2.denominator); return result; } #endif // ARRAY_H