【PAT甲级 - C++题解】1081 Rational Sum

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1081 Rational Sum (pintia.cn)
🔑中文翻译:有理数的和
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

1081 Rational Sum

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

Input Specification:

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.

Output Specification:

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.

Sample Input 1:

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

Sample Output 1:

3 1/3

Sample Input 2:

2
4/3 2/3

Sample Output 2:

2

Sample Input 3:

3
1/3 -1/6 1/8

Sample Output 3:

7/24
题意

给定 N 个有理数,格式为 分子/分母 ,请你计算它们的和。

保证答案中需要出现的所有数字都在 long long 范围内,且保证最终答案为非负数。

另外,如果给定的分数为负数,则符号在分子上。

思路

我们可以一个一个分数进行计算,用两个变量 ab 来计算所有计算结果。

因为题目数据范围比较大,如果直接按照正常逻辑 a / b + c / d = ( a ∗ d + c ∗ b ) / b ∗ d a/b + c/d= (a*d+c*b)/b*d a/b+c/d=(ad+cb)/bd 计算可能会爆 int ,我们需要拆分成三步防止爆 int

  1. 先对给定的分数 c/d 进行化简。
  2. 然后进行运算,为了防止乘数过大,每次乘法前都除以一个 bd 的最大公约数。
  3. 最后再对结果 a/b 进行化简。
代码
#include<bits/stdc++.h>
using namespace std;

typedef long long LL;

//求最大公约数
LL gcd(LL a, LL b)
{
    return b ? gcd(b, a % b) : a;
}

int main()
{
    LL a = 0, b = 1;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        LL c, d;
        scanf("%lld/%lld", &c, &d);

        //先对输入的分数进行化简
        LL t = gcd(c, d);
        c = c / t, d = d / t;

        //乘法可能会爆int,所以计算过程中也除以个最大公约数
        t = gcd(b, d);
        a = d / t * a + b / t * c;
        b = b / t * d;

        //最后再对结果进行化简
        t = gcd(a, b);
        a = a / t, b = b / t;
    }

    if (b == 1) printf("%lld\n", a);
    else
    {
        if (a >= b)    printf("%lld ", a / b), a %= b;
        printf("%lld/%lld\n", a, b);
    }

    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值