A1081. 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
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <iostream> 4 #include <string.h> 5 #include <string> 6 #include <math.h> 7 #include <algorithm> 8 using namespace std; 9 //求最大公约数 10 int gcd(long long a,long long b) 11 { 12 if(b==0)return a; 13 else return gcd(b,a%b); 14 } 15 16 struct Fraction{ 17 long long up; 18 long long down; 19 }; 20 Fraction reduction(Fraction r) 21 { 22 if(r.down<0) 23 { 24 r.up*=(-1); 25 r.down*=(-1); 26 } 27 if(r.up==0) 28 { 29 r.down=1; 30 }else 31 { 32 int d=gcd(r.up,r.down); 33 r.up=r.up/d; 34 r.down/=d; 35 } 36 return r; 37 } 38 39 Fraction add(Fraction a,Fraction b) 40 { 41 Fraction r; 42 r.down=a.down*b.down; 43 r.up=a.up*b.down+a.down*b.up; 44 return reduction(r); 45 } 46 47 void show(Fraction a) 48 { 49 if(a.down==1) 50 printf("%lld",a.up); 51 else if(abs(a.up)>a.down) 52 { 53 printf("%lld %lld/%lld",a.up/a.down,abs(a.up)%a.down,a.down); 54 } 55 else 56 { 57 printf("%lld/%lld",a.up,a.down); 58 } 59 } 60 int main(){ 61 int n; 62 scanf("%d",&n); 63 Fraction sum,temp; 64 sum.up=0;sum.down=1; 65 for(int i=0;i<n;i++) 66 { 67 scanf("%lld/%lld",&temp.up,&temp.down); 68 sum=add(sum,temp); 69 } 70 show(sum); 71 return 0; 72 }