Challenge: Adding Fractions

Lab C++ Intermediate 20 points

Write a struct Fraction with int num, den, an operator+ and an operator<< that prints it as num/den. The result must be in lowest terms (divide by the greatest common divisor). Read two fractions as a b c d (meaning a/b and c/d) and print their sum.

Input

Four positive integers a b c d.

Output

The sum, like 5/6.

Example

Input

1 2 1 3

Output

5/6
Sample input available Sample output available
Editor
C++

Hints

a/b + c/d = (a*d + c*b) / (b*d).

Divide top and bottom by gcd(top, bottom).

operator<< returns ostream& and takes (ostream& out, const Fraction& f).

Solution explanation

With operator+ and operator<< the fraction behaves like a built-in type: cout << x + y just works.

Show solution
#include <iostream>
using namespace std;

int gcd(int a, int b) {
    while (b != 0) {
        int t = a % b;
        a = b;
        b = t;
    }
    return a;
}

struct Fraction {
    int num;
    int den;

    Fraction operator+(const Fraction& o) const {
        int n = num * o.den + o.num * den;
        int d = den * o.den;
        int g = gcd(n, d);
        return {n / g, d / g};
    }
};

ostream& operator<<(ostream& out, const Fraction& f) {
    out << f.num << "/" << f.den;
    return out;
}

int main() {
    Fraction x, y;
    cin >> x.num >> x.den >> y.num >> y.den;
    cout << x + y << "\n";
    return 0;
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD