Summing pairs of fractions S24486


Statement
 

pdf   zip

Write a program to sum a sequence of pairs of fractions. To practice top-down design, the program should be the result of completing the lines of code outlined below.

    
   ....
   
   struct Rational {
        int num; // numerator
        int den; // denominator
    };
    

    //pre: ....
    //post: ....
    int gcd_euclides(...)

    //pre:---
    //post: returns r in simplified form
    Rational simplify(Rational r)
 
    //....
    void write_rational(Rational r) {
        if (r.num == 0) cout << "0";
        else if (r.den == 1) cout << r.num;
        else cout << r.num << "/" << r.den;
    }

    ....
    .... 
    ....

    int main() {
        Rational rat1, rat2, total={0,1};
        while (read_pair_rationals(....)) {
            Rational sum = sum_and_simp(....);
            write_sum(....);
            ...
        }
        write_result(total);
    }

Input

Input consists of sequence of lines. Each line contains four integers a,b,c,da, b, c, d representing fractions ab\frac{a}{b} and cd\frac{c}{d}. It holds b0b \neq 0 and d0d \neq 0

Output

Summation of the pairs of fractions ab+cd\frac{a}{b} + \frac{c}{d} (one per line) and the final sum of all of them at the end. The result fractions need to be simplified: numerator and denominator have no common factors, and the denominator is positive. If a fraction is 0n\frac{0}{n} you should write only 00. If the fraction is n1\frac{n}{1} you should write only nn. Follow the format of examples below.

Public test cases
  • Input

    1 3 2 3
    -1 5 2 10
    34 45 12 12
    

    Output

    1/3 + 2/3 = 1
    -1/5 + 2/10 = 0
    34/45 + 12/12 = 79/45
    Total = 124/45
    
  • Input

    1 2 1 -2
    1 3 2 -3
    3 1 -10 -2
    

    Output

    1/2 + 1/-2 = 0
    1/3 + 2/-3 = -1/3
    3 + -10/-2 = 8
    Total = 23/3
    
  • Input

    -5 -5
    

    Output

    Total = 0
    
  • Information
    Author
    Lluís Marquez
    Language
    English
    Other languages
    Catalan
    Official solutions
    C++
    User solutions
    C++