PTA天梯赛-练习集 L1-009 N个数求和

N个数求和
模拟通分

#include <bits/stdc++.h>
using namespace std;
#define d(x) cout << (x) << endl

typedef long long ll;
const int N = 1e2 + 10;
const int INF = 0x3f3f3f3f;

struct node{
    ll x, y;
    node(ll x, ll y):x(x),y(y){}
    node(){}
};
node arr[N];

node f(node m, node n)
{
    ll num = m.y * n.y / __gcd(m.y, n.y);
    ll num1 = m.x * (num / m.y) + n.x * (num / n.y);
    node ans = node(num1, num);
    return ans;
}

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++){
        ll a, b;
        char c;
        scanf("%lld%c%lld", &a, &c, &b);
        // printf("%d %d\n", a, b);
        arr[i] = node(a, b);
    }
    node ans = arr[0];
    for (int i = 1; i < n; i++){
        ans = f(ans, arr[i]);
        // printf("%d %d\n", ans.x, ans.y);
    }
    ll cntx = ans.x / __gcd(ans.x, ans.y);
    ll cnty = ans.y / __gcd(ans.x, ans.y);
    if(cntx < 0){
        printf("-");
        cntx = -cntx;
    }
    if(cntx == 0){
        printf("0\n");
        return 0;
    }
    if(cntx < cnty){
        printf("%lld/%lld\n", cntx, cnty);
    }else if(cntx == cnty){
        printf("1\n");
    }else{
        if(cntx % cnty == 0){
            printf("%lld\n", cntx / cnty);
        }else{
            ll num1 = cntx / cnty;
            ll num2 = cntx % cnty;
            printf("%lld %lld/%lld\n", num1, num2, cnty);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值