PAT_A1081#Rational Sum
Source:
Description:
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 (≤), 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
whereinteger
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
Keys:
Code:
1 /* 2 Data: 2019-07-05 19:37:00 3 Problem: PAT_A1081#Rational Sum 4 AC: 26:24 5 6 题目大意: 7 给N个分数,求和 8 */ 9 #include<cstdio> 10 #include<algorithm> 11 using namespace std; 12 const int M = 1e3; 13 struct fr 14 { 15 long long up; 16 long long down; 17 }temp; 18 19 int gcd(int a, int b) 20 { 21 if(b==0) return a; 22 else return gcd(b,a%b); 23 } 24 25 fr Reduction(fr s) 26 { 27 if(s.up == 0) 28 s.down = 1; 29 else 30 { 31 int d = gcd(abs(s.up), s.down); 32 s.up /= d; 33 s.down /= d; 34 } 35 return s; 36 } 37 38 fr Add(fr s1, fr s2) 39 { 40 fr s; 41 s.up = s1.up*s2.down+s2.up*s1.down; 42 s.down = s1.down*s2.down; 43 return Reduction(s); 44 } 45 46 int main() 47 { 48 #ifdef ONLINE_JUDGE 49 #else 50 freopen("Test.txt", "r", stdin); 51 #endif 52 53 int n; 54 scanf("%d\n", &n); 55 fr ans = fr{0,1}; 56 for(int i=0; i<n; i++) 57 { 58 scanf("%lld/%lld", &temp.up, &temp.down); 59 ans = Add(ans, temp); 60 } 61 62 if(ans.down==1) 63 printf("%lld\n", ans.up); 64 else if(ans.up >= ans.down) 65 printf("%lld %lld/%lld\n", ans.up/ans.down, abs(ans.up)%ans.down, ans.down); 66 else 67 printf("%lld/%lld\n", ans.up, ans.down); 68 69 return 0; 70 }