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
AC代码
#include <iostream>
using namespace std;
long int GCD(long int x, long int y); //得到x和y的最大公约数
long int LCM(long int x, long int y); //得到x和y的最小公倍数
int main() {
int N;
cin >> N;
int Num[201];
int Z = 0; //积累整数部分
for (int i = 0; i < 2 * N; i += 2) //得到所有分数的分子与分母
scanf("%d/%d", &Num[i], &Num[i + 1]);
long int a1, b1, a2, b2;
a1 = Num[0];
b1 = Num[1];
long int Tmp = GCD(a1, b1);
a1 /= Tmp;
b1 /= Tmp; //实现自身化简
for (int i = 2; i < 2 * N; i += 2) {
a2 = Num[i];
b2 = Num[i + 1];
long int Tmp1 = GCD(a2, b2);
a2 /= Tmp1;
b2 /= Tmp1; //实现待相加的分数的自身化简
long int LCM1 = LCM(b1, b2); //求两个分数分母的最小公倍数
long int Tmpa1 = a1*(LCM1 / b1) + a2*(LCM1 / b2); //得到相加后未处理的分子
long int GCD1 = GCD(Tmpa1, LCM1);
a1 = Tmpa1 / GCD1;
b1 = LCM1 / GCD1; //得到化简完毕的分数
if (b1 == 1) { Z += a1; a1 = 0; } //得到整数的情况
if (a1 > b1) { Z += (a1 / b1); a1 = a1 % b1; } //将假分数化为整数和真分数
}
int flag = 0;
if (Z) { cout << Z; flag = 1; }
if (a1) {
if (flag) cout << ' ';
cout << a1 << '/' << b1 << endl;
}
if (Z == 0 && a1 == 0) cout << '0'; //确保如果所有结果都为零时正常输出结果
return 0;
}
long int LCM(long int x, long int y) {
return x*y/GCD(x, y);
}
long int GCD(long int x, long int y){
return y == 0 ? x : GCD(y, x%y);
}