Fraction Arithmetic

Lab C++ Advanced 30 points

Write class Fraction (always reduced, positive denominator) with + - * /, ==, < and <<. Read two fractions a/b c/d and print the sum, difference, product, quotient and whether a/b < c/d.

Input

One line: a/b c/d (non-zero denominators, c ≠ 0).

Output

Five lines.

Example

Input

1/2 1/3

Output

5/6
1/6
1/6
3/2
false
Sample input available Sample output available
Editor
C++

Hints

Normalise in the constructor so every operation's result is reduced automatically.

Solution explanation

Putting all the reduction logic in one constructor keeps each operator to one line.

Show solution
#include <iostream>
#include <numeric>
#include <cstdio>
using namespace std;

class Fraction {
public:
    Fraction(long long n = 0, long long d = 1) {
        if (d < 0) { n = -n; d = -d; }
        long long g = gcd(n < 0 ? -n : n, d);
        num_ = n / g;
        den_ = d / g;
    }
    friend Fraction operator+(Fraction a, Fraction b) { return {a.num_ * b.den_ + b.num_ * a.den_, a.den_ * b.den_}; }
    friend Fraction operator-(Fraction a, Fraction b) { return {a.num_ * b.den_ - b.num_ * a.den_, a.den_ * b.den_}; }
    friend Fraction operator*(Fraction a, Fraction b) { return {a.num_ * b.num_, a.den_ * b.den_}; }
    friend Fraction operator/(Fraction a, Fraction b) { return {a.num_ * b.den_, a.den_ * b.num_}; }
    friend bool operator<(Fraction a, Fraction b) { return a.num_ * b.den_ < b.num_ * a.den_; }
    friend ostream &operator<<(ostream &out, Fraction f) {
        out << f.num_;
        if (f.den_ != 1) out << "/" << f.den_;
        return out;
    }

private:
    long long num_, den_;
};

int main() {
    long long a, b, c, d;
    char slash;
    cin >> a >> slash >> b >> c >> slash >> d;
    Fraction x(a, b), y(c, d);
    cout << x + y << "\n" << x - y << "\n" << x * y << "\n" << x / y << "\n" << boolalpha << (x < y) << "\n";
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD