PAT1081 Rational Sum

54 篇文章 1 订阅

原文:我的个人博客

原题链接

1081 Rational Sum

思路

  为了避免超出long的范围,每一次的累加都将分子分母做相应的处理。

代码

#include <iostream>
using namespace std;
long long n=0,m=1,tmp;
long gcd(long a,long b){
    if(a<b) swap(a,b);
    if(a%b==0)return b;
    else return gcd(b,a%b);
}
long lcm(long a,long b){
    return a*b/gcd(a,b);
}
void add(long long a1,long long b1){
    //求n/m+a1/b1并赋值给n/m
    n = n*b1+a1*m;
    m = m*b1;
//  cout<<n<<'\t'<<m<<endl;
    if(n<0){
        tmp=gcd(-n,m);
    }else if(n>0){
        tmp=gcd(n,m);
    }else if(n==0){
        n=0;
        m=1;
        return;
    }
    n/=tmp;
    m/=tmp;
/// cout<<n<<'\t'<<m<<endl;
}
//化为最简型 
void func(){
    if(n==0){
        cout<<0;
        return;
    }else if(m==0){
        cout<<"Inf";
        return;
    }
    if(n<0){
        cout<<"-";
        n = -n;
    }
    long long x = n/m;
    if(x!=0)cout<<x;
    if(n%m==0) return;//没有分数部分
    if(x!=0) cout<<" ";
    n -= x*m;
//  cout<<"n="<<n<<'\t'<<"m="<<m<<endl;
    long long t = gcd(n,m);
    n/=t;
    m/=t;
    cout<<n<<'/'<<m;
}
int main(){
    int N;
    cin>>N;
    for(int i=0;i<N;i++){
        long long a,b;
        scanf("%lld/%lld",&a,&b);
//      cout<<a<<"\t"<<b<<endl;
        add(a,b);
//      cout<<n<<'/'<<m<<endl;
    } 
    func();
    return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值