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;
}


目录
相关文章
|
8月前
|
机器学习/深度学习
计算sum=1+2...+n,要求number和sum的类型都是int,且sum在32位以内~
计算sum=1+2...+n,要求number和sum的类型都是int,且sum在32位以内~
|
12月前
|
C++
【PAT甲级 - C++题解】1081 Rational Sum
【PAT甲级 - C++题解】1081 Rational Sum
69 0
|
算法
1081. Rational Sum (20)
1081. Rational Sum (20)
94 0
1081. Rational Sum (20)
|
SQL
sum函数
sum函数
89 0
|
文件存储
Sum of Round Numbers
Sum of Round Numbers
86 0
Sum of Round Numbers
【1081】Rational Sum (20 分)
【1081】Rational Sum (20 分) 【1081】Rational Sum (20 分)
74 0
【1088】Rational Arithmetic (20 分)
【1088】Rational Arithmetic (20 分) 【1088】Rational Arithmetic (20 分)
84 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.
775 0
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
769 0