Printing Objects

Lab C++ Intermediate 20 points

Write class Fraction that stores a reduced fraction (use std::gcd from <numeric>) and overload operator<< to print it as p/q (or just p when q is 1). Read fractions and print them reduced.

Input

n, then n lines a b (b > 0).

Output

n lines.

Example

Input

4
6 8
10 5
-9 12
0 7

Output

3/4
2
-3/4
0
Sample input available Sample output available
Editor
C++

Hints

A friend operator<< can read private members.

Return the stream so calls can be chained.

Solution explanation

Overloading << lets your class print with cout like built-in types.

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

class Fraction {
public:
    Fraction(long long num, long long den) {
        long long g = gcd(num < 0 ? -num : num, den);
        num_ = num / g;
        den_ = den / g;
    }
    friend ostream &operator<<(ostream &out, const Fraction &f) {
        out << f.num_;
        if (f.den_ != 1) out << "/" << f.den_;
        return out;
    }

private:
    long long num_, den_;
};

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        long long a, b;
        cin >> a >> b;
        cout << Fraction(a, b) << "\n";
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD