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
题意:给出N个分数,计算总和,答案以分数或带分数组成。
思路:对于分数的计算,先要将分数定义为一个结构体,up为分子,down为分母,和计算:分子=(分子1*分母2+分子2*分母1),分母=(分母1*分母2)减法同理,乘除更简单,计算过后还要化简:
1.如果说分母为负,那当然不行,就要分子分母同乘-1,将分母化为正。
2.如果分子为0,就将分母设置为1,方便之后直接输出分子0.
3.约分:分子分母同除最大公约数。
最大公约数:辗转相除(代码中的gcd函数,背下来方便直接使用)
最大公倍数:(a*b)/gcd(a,b)
最后,输出: 分母为1直接输出分母
分子绝对值大于分母就要化为带分数,整数=分子/分母,分数的小数为分子%分母,分母不变。
分子绝对值小于分母直接输出。
#include<bits/stdc++.h>
using namespace std;
int n;
typedef long long ll;
struct fra{
ll up,down;
};
ll gcd(ll a,ll b){
if(b==0){
return a;
}else{
return gcd(b,a%b);
}
}
fra reduction(fra result){
int d;
if(result.down<0){
result.down=-result.down;
result.up=-result.up;
}
if(result.up==0){
result.down=1;
}else{
d=gcd(abs(result.up),abs(result.down));
result.up/=d;
result.down/=d;
}
return result;
}
fra add(fra sum,fra temp){
fra result;
result.up=sum.up*temp.down+temp.up*sum.down;
result.down=sum.down*temp.down;
return reduction(result);
}
void showresult(fra sum){
reduction(sum);
if(sum.down==1){
printf("%lld\n",sum.up);
}else if(abs(sum.up)>sum.down){
printf("%lld %lld/%lld\n",sum.up/sum.down,abs(sum.up)%sum.down,sum.down);
}else{
printf("%lld/%lld\n",sum.up,sum.down);
}
}
int main(){
cin>>n;
fra sum,temp;
sum.up=0;
sum.down=1;
while(n--){
scanf("%lld/%lld",&temp.up,&temp.down);
sum=add(sum,temp);
}
showresult(sum);
}