PTA——L1-009 N个数求和

343 阅读2分钟

PTA——L1-009 N个数求和

题目详情 - L1-009 N个数求和 (pintia.cn)

本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数分子/分母的形式给出的,你输出的和也必须是有理数的形式。

输入格式:

输入第一行给出一个正整数N(≤100)。随后一行按格式a1/b1 a2/b2 ...给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。

输出格式:

输出上述数字和的最简形式 —— 即将结果写成整数部分 分数部分,其中分数部分写成分子/分母,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。

输入样例1:

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

输出样例1:

3 1/3

输入样例2:

2
4/3 2/3

输出样例2:

2

输入样例3:

3
1/3 -1/6 1/8

输出样例3:

7/24

问题解析

可以先回想一下,平时是如何进行分数运算的。

  • 如果分母相同,则直接分子相加;
  • 如果分母不相同,则进行通分:把分母变得一样,两边的分子乘上对应变化的倍数。

在这题里,我们也是如此。

通分可以取两边分母的最小公倍数:两个分母相乘再除去它们的最大公约数。

然后再把分子相加。

最后输出结果,至于要分子分母没有公约数,则让他们除去他们之间的最大公约数即可。

AC代码

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include <random>
#include<numeric>
#include<string>
#include<string.h>
#include<iterator>
#include<fstream>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
#include<queue>
#include<iomanip>
#include<bitset>//#pragma GCC optimize(2)
//#pragma GCC optimize(3)#define endl '\n'
#define int ll
#define PI acos(-1)
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PII;
const int N = 5e5 + 50, MOD = 998244353;
​
PII get_num(string& s)
{
    int x = 0, y = 0, idx = 0;
    bool flag = true;
    if (s[0] == '-')
    {
        flag = false;
        idx++;
    }
    while (s[idx] != '/')
    {
        x *= 10;
        x += (s[idx] - '0');
        idx++;
    }
    idx++;
    while (idx < s.size())
    {
        y *= 10;
        y += (s[idx] - '0');
        idx++;
    }
    if (!flag)x *= -1;
    return { x,y };
}
​
int gcd(int a, int b)
{
    return a % b == 0 ? b : gcd(b, a % b);
}
​
int mylcm(int x, int y)
{
    int z = gcd(x, y);
    return x * y / z;
}
​
void solve()
{
    int n;
    cin >> n;
    int fz = 0, fm = 1;
    string s;
    for (int i = 1; i <= n; i++)
    {
        cin >> s;
        auto t = get_num(s);
        int z = mylcm(fm, t.second);
        fz *= (z / fm);
        t.first *= (z / t.second);
        fz += t.first;
        fm = z;
    }
    int x = fz / fm;
    fz %= fm;
    int y = abs(gcd(fz, fm));
    fz /= y;
    fm /= y;
    if (x != 0)cout << x;
    if (x != 0 && fz != 0)cout << " ";
    if (fz != 0)cout << fz << "/" << fm << endl;
    if (x == 0 && fz == 0)cout << 0 << endl;
}
​
signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int t = 1;
    //cin >> t;
    while (t--)
    {
        solve();
    }
    return 0;
}