C++: Adding fractions with operator+

Complete the class Fraction: a constructor that stores the fraction reduced (lowest terms, denominator positive), operator+, and operator<< that prints num/den, or just num when the denominator is 1. Then add pairs of fractions.

What to build

A Fraction class that adds fractions and prints them in lowest terms.

Requirements

  • Reduce every fraction in the constructor, keeping the denominator positive.
  • Write operator+ to return a new fraction.
  • Write operator<< to print num/den, or just num when the denominator is 1.

Input

The first line has q (1 ≤ q ≤ 100). Each of the next q lines has four whole numbers a b c d (b and d are not 0; all between -1000 and 1000), meaning a/b + c/d.

Output

One line per sum, in lowest terms.

Constraints

1 ≤ q ≤ 100, and the numbers are from -1000 to 1000, with no zero denominator.

Example

Input:

2
1 2 1 3
1 4 1 4

Output:

5/6
1/2

Why it works

Reducing in the constructor means every fraction is always stored in lowest terms, so the sum and the printing never have to think about it.

Examples

Example 1 · Input
2
1 2 1 3
1 4 1 4
Expected output
5/6
1/2
Example 2 · Input
1
1 2 1 2
Expected output
1

Hints

Hint 1

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

Hint 2

Reduce in the constructor: divide both parts by their gcd, and keep the denominator positive.

Hint 3

operator<< prints num/den, or just num when den is 1.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;

long long gcd(long long a, long long b) {
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    while (b != 0) {
        long long t = a % b;
        a = b;
        b = t;
    }
    return a;
}

class Fraction {
    long long num, den;
public:
    Fraction(long long n, long long d) {
        if (d < 0) {
            n = -n;
            d = -d;
        }
        long long g = gcd(n, d);
        if (g == 0) g = 1;
        num = n / g;
        den = d / g;
    }
    Fraction operator+(const Fraction& o) const {
        return Fraction(num * o.den + o.num * den, den * o.den);
    }
    friend ostream& operator<<(ostream& out, const Fraction& f);
};

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

int main() {
    int q;
    cin >> q;
    for (int i = 0; i < q; i++) {
        long long a, b, c, d;
        cin >> a >> b >> c >> d;
        cout << Fraction(a, b) + Fraction(c, d) << endl;
    }
    return 0;
}

Lesson: Operator overloading →