#include using namespace std; struct fraction { int top, bot; }; int gcd_version1(int a, int b) // takes a long time for big numbers { int sml; if (a < b) sml = a; else sml = b; for (int d = sml; d > 1; d -= 1) { if (a % d == 0 && b % d == 0) return d; } return 1; } int gcd(int a, int b) // Euclid's algorithm from about 300 BC { while (b != 0) { int t = b; b = a % b; a = t; } return a; } fraction norm(fraction X) { int d = gcd(X.top, X.bot); if (d == 1) return X; fraction R; R.top = X.top / d; R.bot = X.bot / d; return R; } fraction add(fraction A, fraction B) { fraction R; R.top = A.top*B.bot + B.top*A.bot; R.bot = A.bot*B.bot; return norm(R); } fraction sub(fraction A, fraction B) { fraction R; R.top = A.top*B.bot - B.top*A.bot; R.bot = A.bot*B.bot; return norm(R); } fraction mul(fraction A, fraction B) { fraction R; R.top = A.top*B.top; R.bot = A.bot*B.bot; return norm(R); } fraction div(fraction A, fraction B) { fraction R; R.top = A.top*B.bot; R.bot = A.bot*B.top; return norm(R); } void print(fraction X) { if (X.top == 0) cout << "0"; else if (X.bot == 1) cout << X.top; else if (X.top > X.bot) cout << " " << X.top/X.bot << "+" << X.top%X.bot << "/" << X.bot << " "; else cout << " " << X.top << "/" << X.bot << " "; } int main() { while (true) { fraction a, b; cout << "Enter A's top and bottom: "; cin >> a.top >> a.bot; cout << "Enter B's top and bottom: "; cin >> b.top >> b.bot; cout << "A + B = "; print(add(a, b)); cout << "\n"; cout << "A - B = "; print(sub(a, b)); cout << "\n"; cout << "A * B = "; print(mul(a, b)); cout << "\n"; cout << "A / B = "; print(div(a, b)); cout << "\n"; } }