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
-----------------------------------这是题目和解题的分割线-----------------------------------
对最大公约数和最小公倍数的考察。
注意,数据范围in the range of long int,当两个数据相乘的时候,最大可以达到long long。
给出几组容易错的数据
2 -4/3 8/6 // 0
2 1/3 -1/2 // -1/6
2 13/6 -7/6 // 1
不过这道题的数据十分非常相当弱,一些特例不通过也不会报错。
#include<stdio.h>
#include<stdlib.h>
struct node
{
long long x,y;
}num[105],tmp,sum;
//最大公约数
long long findGCD(long long a,long long b)
{
if(b==0) return a;
return findGCD(b,a%b);
}
node sumFx(node a,node b)
{
long long maxG,minG,x,newx,newy;
maxG = findGCD(a.y,b.y);
//最小公倍数 = a*b/最大公约数 新的分母
minG = (a.y)*(b.y)/maxG;
//新的分子
x = minG/a.y*a.x+minG/b.y*b.x;
//约分(abs保证最大公约数为正数)
tmp.x = x/findGCD(abs(x),minG);
tmp.y = minG/findGCD(abs(x),minG);
return tmp;
}
int main()
{
int i,n;
long long x,y,minG,maxG;
scanf("%d",&n);
if(n==0) {printf("0");return 0;}
scanf("%lld/%lld",&sum.x,&sum.y);
for(i=1;i<n;i++)
{
scanf("%lld/%lld",&num[i].x,&num[i].y);
if(num[i].x==0) continue;
sum = sumFx(num[i],sum); //两两相加
}
//printf("%lld/%lld\n",sum.x,sum.y);
if(!sum.x) {printf("0");return 0;}
//如果分母大于等于分子,需比较绝对值
if(abs(sum.x)>=abs(sum.y))
{
printf("%lld",sum.x/sum.y);
long long t = sum.x-sum.x/sum.y*sum.y;
if(t) printf(" %lld/%lld",t,sum.y);
}
else printf("%lld/%lld",sum.x,sum.y);
return 0;
}