时间限制 1000 ms 内存限制 65536 KB 代码长度限制 100 KB 判断程序
题目描述
Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.
输入描述:
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.
输出描述:
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.
输入例子:
5
2/5 4/15 1/30 -2/60 8/3
输出例子:
3 1/3
注意事项:
1.分子能被分母整除,则直接输出整除结果
2.分子小于分母时,直接输出分子/分母最简形式
3.分子为0时,结果为0,而不是0/分母
def yue(a,b):
#约分
if a<b:
a,b=b,a
r=2
for i in range(abs(b)):
if a%r==0 and b%r==0:
a=a/r
b=b/r
else:
r+=1
return int(a),int(b)
N=int(input())
number=[x for x in input().split(" ")]
numerator=[] #分子集合
denominator=[] #分母集合
mulDeno=1 #所有分母乘积
for i in range(N):
num=number[i].split("/")
a=num[0]
b=num[1]
numerator.append(int(a))
denominator.append(int(b))
mulDeno*=int(b)
sum=0
for i in range(N):
sum+=mulDeno/denominator[i]*numerator[i]
if sum%mulDeno==0:
print(int(sum/mulDeno))
else:
count = 0
if sum < 0:
sum = abs(sum)
while sum > mulDeno:
sum -= mulDeno
count += 1
mulDeno, sum = yue(int(sum), int(mulDeno))
sum=-sum
else:
while sum > mulDeno:
sum -= mulDeno
count += 1
mulDeno, sum = yue(int(sum), int(mulDeno))
if count == 0:
if sum == 0:
print(0)
else:
print(str(sum) + "/" + str(mulDeno))
else:
print(str(count) + " " + str(sum) + "/" + str(mulDeno))