PAT 1081 Rational Sum python解法

1081 Rational Sum (20 分)
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

题意:求几个分数的和,结果化为最简分数。

解题思路:
1.分数计算主要问题在于求最大公约数和最小公倍数,最大公约数可以使用辗转相除法,最小公倍数可由两数乘积/最大公倍数得到。
2.两个分数相加,先要把两个分母的最小公倍数求出来,也就是通分,相加之后再对和进行化简,也是就求分子分母的最大公约数。
3.多个数相加就是循环调用两个分数相加的函数。
4.最后对结果进行格式化输出,需要几个判断,有分子为0,分母为1,分子大于分母,以及分子为负数的情况。

n = int(input())
l = input().split()
#l = ['2/5', '4/15', '1/30', '-2/60', '8/3']
#l = ['4/3', '2/3']
#l = ['1/3', '-1/6', '1/8']
numerators = []
denominators = []
def gcd(n1,n2):#greatest common divisor
    return gcd(n2, n1 % n2) if n2 else n1
#    if n2:
#        return gcd(n2, n1 % n2)
#    else: 
#        return n1
def lcm(n1,n2):#lowest common multiple
    return n1*n2//gcd(n1,n2)
def  rational_sum(r1, r2):
    n1, d1 = map(int,r1.split('/'))
    n2, d2 = map(int,r2.split('/'))
    d3 = lcm(d1, d2)
    n3 = n1*(d3//d1) + n2*(d3//d2)
    if n3:
        gcd1 = gcd(abs(n3),d3)
        d3 = d3//gcd1
        n3 = n3//gcd1
    return str(n3)+'/'+str(d3)
s = l[0]
for i in range(1,len(l)):
    s = rational_sum(s,l[i])
#print(s)
n1, d1 = map(int,s.split('/'))
if d1 == 1:
    print(n1)
elif n1 == 0:
    print(n1)
elif abs(n1) > d1:
    if n1>0:
        print('%d %d/%d'%(n1//d1,n1%d1,d1))
    else:
        print('%d %d/%d'%((n1//d1)+1,abs(n1)%d1,d1))
else:
    print(s)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

D_ry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值