A1081 Rational Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<bits/stdc++.h> 
#define MAX 110
using namespace std;
struct fract{
int a,b;

};
int n;
int gcd(int a,int b){
if(a%b==0) return b;
gcd(b,a%b);
}
fract f[MAX];
fract redu(fract m){
fract res;
if(m.b<0){
m.b=-m.b;
m.a=-m.a;
}
int g=gcd(abs(m.a),abs(m.b));
res.a=m.a/g;
res.b=m.b/g;
return res;
}
fract add(fract m,fract n){
fract res;
res.b=m.b*n.b;
res.a=m.a*n.b+n.a*m.b;
return redu(res);


}
void show(fract ff){
if(ff.b==1) {
cout<<ff.a<<endl;
return;

}
else if(abs(ff.a)>ff.b){
int t=ff.a/ff.b;
int wei=ff.a-ff.b*t;
cout<<t<<" "<<wei<<"/"<<ff.b<<endl;
}
else cout<<ff.a<<"/"<<ff.b<<endl;
}
int main(){
fract sum;
sum.a=0;
sum.b=1;
cin>>n;
for(int i=0;i<n;i++){
scanf("%d/%d",&f[i].a,&f[i].b);
}
for(int i=0;i<n;i++){
sum=add(sum,f[i]);
}
show(sum);

}