1081. Rational Sum (20)

简介: #include using namespace std;long gcd(long a, long b){ while (a) { long t = a; a = b % ...
 
 
#include <iostream>
using namespace std;

long gcd(long a, long b){
    while (a) {
        long t = a;
        a = b % a;
        b = t;
    }
    return b;
}

int main(int argc, const char * argv[]) {
    int n;
    cin >> n;
    long a, b, n1, n2;
    scanf("%ld/%ld", &a, &b);
    
    for (int i = 0; i < n - 1; i++) {
        scanf("%ld/%ld", &n1, &n2);
        a = a * n2 + n1 * b;
        b = b * n2;
        long t0 = gcd(abs(a), abs(b));
        a = a / t0;
        b = b / t0;
    }

    n1 = a / b;
    n2 = a % b;
    if (n2) {
        if (n1) {
            cout << n1 << ' ';
        }
        cout << n2 << '/' << b << endl;
    }else{
        cout << n1 << endl;
    }
    
    return 0;
}


目录
相关文章
|
机器学习/深度学习
计算sum=1+2...+n,要求number和sum的类型都是int,且sum在32位以内~
计算sum=1+2...+n,要求number和sum的类型都是int,且sum在32位以内~
|
C++
【PAT甲级 - C++题解】1081 Rational Sum
【PAT甲级 - C++题解】1081 Rational Sum
98 0
|
算法
1081. Rational Sum (20)
1081. Rational Sum (20)
136 0
1081. Rational Sum (20)
|
SQL
sum函数
sum函数
145 0
|
人工智能 BI
CodeForces - 1485D Multiples and Power Differences (构造+lcm)
CodeForces - 1485D Multiples and Power Differences (构造+lcm)
84 0
【1081】Rational Sum (20 分)
【1081】Rational Sum (20 分) 【1081】Rational Sum (20 分)
99 0
【1088】Rational Arithmetic (20 分)
【1088】Rational Arithmetic (20 分) 【1088】Rational Arithmetic (20 分)
103 0
【1059】Prime Factors (25 分)
【1059】Prime Factors (25 分) 【1059】Prime Factors (25 分)
101 0
1088. Rational Arithmetic (20)
For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
798 0