• 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
    ", num);
            // else
            // printf("0");
        }
        else
        {
            if (num != 0)
                printf("%lld %lld/%lld
    ", num, sum, minn);
            else
                printf("%lld/%lld
    ", sum, minn);
        }
        return 0;
    }
    View Code
  • 相关阅读:
    golang的缓冲channel简单使用
    golang协程同步的几种方法
    红黑树原理详解及golang实现
    go路由httprouter中的压缩字典树算法图解及c++实现
    golang编译源代码和交叉编译方法
    cmake使用笔记
    如何用redis设计数据库初探
    muduo学习笔记(六) 多线程的TcpServer
    利用 Blob 处理 node 层返回的二进制文件流字符串并下载文件
    数据量庞大的分页穿梭框实现
  • 原文地址:https://www.cnblogs.com/kuroko-ghh/p/10268744.html
Copyright © 2020-2023  润新知