题目描述
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.
#include<iostream>
using namespace std;
long int lcm(long int m, long int n)
{
while(n != 0)
{
long int z = m % n;
m = n;
n = z;
}
return m;
}
int main()
{
int t;
long int a[101], b[101], res;
long int e, f;
long int tempGcd1,tempLcm1, tempGcd2;
long int p, q;
long int u, v;
int i;
scanf("%d",&t);
for(i = 0; i < t; i++)
{
scanf("%ld/%ld",&a[i],&b[i]);
}
p = b[0]; //分母1
q = b[1]; //分母2
u = a[0]; //分子1
v = a[1]; //分子2
for(i = 0; i < t-1; i++)
{
v = a[i+1];
q = b[i+1];
tempGcd1 = lcm(p,q); //最大公约数
tempLcm1 = p * q / tempGcd1; //最小公倍数
e = u * (tempLcm1 / p); //通分后分子1
f = v *(tempLcm1 / q); //通分后分子2
//printf("%ld/%ld ",e+f,tempLcm1);
//对结果进行约分
long int tempNumerator;
if(e + f >= 0)
{
tempNumerator = e + f;
}
else
{
tempNumerator = -1*(e + f);
}
tempGcd2 = lcm(tempNumerator,tempLcm1);
p = tempLcm1 / tempGcd2;
u = (e + f) / tempGcd2;
//printf("%ld/%ld ",u,p);
}
if(u == 0)
{
printf("%ld",0);
}
else if(u < p)
{
if(p == 1)
{
printf("%ld",u);
}
else
printf("%ld/%ld",u, p);
}
else
{
res = u / p;
if(u-res*p == 0)
{
printf("%ld",res);
}
else {
printf("%ld %ld/%ld",res,u - res*p, p);
}
}
return 0;
}