PAT-Rational Sum (20)

题目描述

Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.

输入描述:

Each input file contains one test case. 
Each case starts with a positive integer N (<=100), followed in the next line N rational numbers "a1/b1 a2/b2 ..." where all the numerators and denominators are in the range of "long int".
If there is a negative number, then the sign must appear in front of the numerator.


输出描述:

For each test case, output the sum in the simplest form "integer numerator/denominator" 
where "integer" is the integer part of the sum, "numerator" < "denominator", and the numerator and the denominator have no common factor.
You must output only the fractional part if the integer part is 0.

输入例子:

5
2/5 4/15 1/30 -2/60 8/3

输出例子:

3 1/3


要注意一些坑,比如最大公因数如果为负数要取反,确保负号在分子上。
结果sum为0时输出0;分子小于分母,结果的分子为分母整数倍数部分为空;求和的分子如果为分母的整数倍,则分数部分为空;
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
ll a[110], b[110];
int main()
{
    //freopen("in.txt", "r", stdin);
    int N;
    scanf("%d", &N);
    scanf("%lld/%lld", &a[0], &b[0]);
    ll minn = b[0];
    int gcd;
    for (int i = 1; i < N; ++i)
    {
        scanf("%lld/%lld", &a[i], &b[i]);
        gcd = __gcd(minn, b[i]);
        if (gcd < 0)gcd = -gcd;
        minn = minn / gcd * b[i];
    }
    ll sum = 0;
    for (int i = 0; i < N; i++)
    {
        a[i] = minn / b[i] * a[i];
        sum += a[i];
    }
    if (sum == 0) {printf("0"); return 0;}
    ll num = sum / minn;
    sum = sum - num * minn;
    //cout<<sum<<endl;
    if (sum != 0)
    {
        ll k = __gcd(sum, minn);
        if(k<0)k=-k;
        minn /= k;
        sum /= k;
    }
    //cout<<sum<<endl;
    if (sum == 0)
    {
        if (num != 0)
            printf("%lld\n", num);
        // else
        // printf("0");
    }
    else
    {
        if (num != 0)
            printf("%lld %lld/%lld\n", num, sum, minn);
        else
            printf("%lld/%lld\n", sum, minn);
    }
    return 0;
}
View Code

 

posted @ 2019-01-14 19:58  besti_kuroko  阅读(187)  评论(0编辑  收藏  举报