#include using namespace std; struct rational { int top, bot; }; 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; } void simplify(rational & a) { if (a.top == 0) { a.bot = 1; return; } int d = gcd(a.top, a.bot); if (d != 1) { a.top /= d; a.bot /= d; } if (a.bot < 0) { a.bot = - a.bot; a.top = - a.top; } } rational fraction(int t, int b) { rational r; r.top = t; r.bot = b; simplify(r); return r; } void print(rational r) { cout << r.top << "/" << r.bot; } rational multiply(rational a, rational b) { rational r; r.top = a.top * b.top; r.bot = a.bot * b.bot; simplify(r); return r; } rational divide(rational a, rational b) { rational r; r.top = a.top * b.bot; r.bot = a.bot * b.top; simplify(r); return r; } rational add(rational a, rational b) { rational r; r.top = a.top * b.bot + b.top * a.bot; r.bot = a.bot * b.bot; simplify(r); return r; } rational subtract(rational a, rational b) { rational r; r.top = a.top * b.bot - b.top * a.bot; r.bot = a.bot * b.bot; simplify(r); return r; } void one_test(string s, rational a, rational b, rational c) { print(a); cout << " " << s << " "; print(b); cout << " is "; print(c); cout << "\n"; } void test(rational a, rational b) { one_test("plus", a, b, add(a, b)); one_test("minus", a, b, subtract(a, b)); one_test("times", a, b, multiply(a, b)); one_test("divided by", a, b, divide(a, b)); } rational ask(string prompt) { rational r; cout << prompt << ", top then bottom: "; cin >> r.top >> r.bot; simplify(r); return r; } int main() { while (true) { rational a = ask("A"); rational b = ask("B"); test(a, b); } }