#include using namespace std; int gcd(int a, int b) { for (int pd = min(a, b); pd > 1; pd -= 1) if (a % pd == 0 && b % pd == 0) return pd; return 1; } struct rational { int top, bot; void simplify() { if (top == 0) { bot = 1; return; } int d = gcd(top, bot); if (d != 1) { top /= d; bot /= d; } if (bot < 0) { bot = - bot; top = - top; } } rational(int t, int b) { top = t; bot = b; simplify(); } void print(ostream & out) { if (top < 0) { out << "-"; top = - top; } if (bot == 1) out << top; else if (top > bot) { int whole = top / bot; int newtop = top - whole * bot; out << whole << "+" << newtop << "/" << bot; } else out << top << "/" << bot; } rational operator*(rational b) { return rational(top * b.top, bot * b.bot); } rational operator/(rational b) { return rational(top * b.bot, bot * b.top); } rational operator+(rational b) { return rational(top * b.bot + b.top * bot, bot * b.bot); } rational operator-(rational b) { return rational(top * b.bot - b.top * bot, bot * b.bot); } rational & operator*=(rational b) { top *= b.top; bot *= b.bot; simplify(); return * this; } rational & operator/=(rational b) { top *= b.bot; bot *= b.top; simplify(); return * this; } rational & operator+=(rational b) { int newbot = bot * b.bot; top = top * b.bot + b.top * bot; bot = newbot; simplify(); return * this; } rational & operator-=(rational b) { int newbot = bot * b.bot; top = top * b.bot - b.top * bot; bot = newbot; simplify(); return * this; } }; ostream & operator<<(ostream & out, rational a) { a.print(out); return out; } void one_test(string s, rational a, rational b, rational c) { cout << a << " " << s << " " << b << " is " << c << "\n"; } void test(rational a, rational b) { one_test("plus", a, b, a + b); one_test("minus", a, b, a - b); one_test("times", a, b, a * b); one_test("divided by", a, b, a / b); one_test("complicated thing", a, b, (a + b) * (a - b)); } rational ask(string prompt) { int t, b; cout << prompt << ", top then bottom: "; cin >> t >> b; return rational(t, b); } int main() { rational w(3, 4); rational x(7, 8); rational y(1, 10); rational z(3, 2); w += x; w -= y; w *= z; cout << "(3/4 + 7/8 - 1/10) * 3/2 = " << w << "\n"; while (true) { rational a = ask("A"); rational b = ask("B"); test(a, b); } }