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
结尾无空行
折磨点请看代码里的注解:(出错测试点3)
总结就是尽量用最大的、不会溢出的类型存储数据
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
long long gcd(long long a,long long b){
return b == 0?a:gcd(b,a % b);
}
void isout(long long a,long long b){
if(abs(a) < b){
cout << a << '/' << b << endl;
return;
}
long long c = 0;
c = a / b;
a %= b;
if(a == 0){
cout << c << endl;
}
else{
cout << c << ' ' << a << '/' << b << endl;
}
return;
}
int main(){
int n;
cin >> n;
vector<int> numerator;
vector<int> denominator;
for(int i = 0;i < n;++i){
int k,l;
scanf("%d/%d",&k,&l);
if(k == 0||l == 0){
continue;
}
else{
numerator.push_back(k);
denominator.push_back(l);
}
}
int len = numerator.size();
///
long long a = numerator[0],b = denominator[0];
//
for(int i = 1;i < len;++i){
//测试点出错的情况是c和d设置为int时a和b设置为long long
//会出错,其余情况包括将数组改为int也是一样不会出错,
//不知道为什么,只能默认用最大的存储方式存储了
long long c = numerator[i],d = denominator[i];
//
a = a * d / gcd(b,d);
c = c * b / gcd(b,d);
a += c;
b = b * d / gcd(b,d);
}
if(a == 0){
cout << 0 << endl;
}
else{
long long temp = gcd(abs(a),b);
a /= temp;
b /= temp;
isout(a,b);
}
return 0;
}