pat1081. Rational Sum (20)

1081. Rational Sum (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

提交代码

测试数据比较弱。如果要算:(2^63)/(3)+(1)/(5)    怎么办??

 1 #include<cstdio>
 2 #include<stack>
 3 #include<algorithm>
 4 #include<iostream>
 5 #include<stack>
 6 #include<set>
 7 #include<map>
 8 using namespace std;
 9 long long gcd(long long a,long long b)
10 {
11     if(b==0)
12     {
13         return a;
14     }
15     return gcd(b,a%b);
16 }
17 int main()
18 {
19     //freopen("D:\INPUT.txt","r",stdin);
20     int n,i;
21     long long fz,ffz,fm,ffm,com;
22     while(scanf("%d",&n)!=EOF)
23     {
24         scanf("%lld/%lld",&fz,&fm);
25         com=gcd(fz,fm);
26         fz/=com;
27         fm/=com;
28         for(i=1; i<n; i++)
29         {
30             //cout<<"i: "<<i<<endl;
31             scanf("%lld/%lld",&ffz,&ffm);
32             com=gcd(fm,ffm);
33             //cout<<"com:  "<<com<<endl;
34             ffz=ffz*(fm/com);
35             //cout<<"ffz:  "<<ffz<<endl;
36             fm=fm*(ffm/com);
37             //cout<<"fm:  "<<fm<<endl;
38             fz=fz*(ffm/com);
39             //cout<<"fz:  "<<ffm<<endl;
40             fz+=ffz;
41             //cout<<"fz:  "<<fz<<endl;
42             com=gcd(fz,fm);
43             //cout<<"com:  "<<com<<endl;
44             fz/=com;
45             //cout<<"fz:  "<<fz<<endl;
46             fm/=com;
47             //cout<<"fm:  "<<fm<<endl;
48         }
49 
50         //cout<<fz<<" "<<fm<<endl;
51 
52         if(fz%fm==0) //可以整除
53         {
54             printf("%lld
",fz/fm);
55         }
56         else
57         {
58             if(fz/fm>1)
59             {
60                 printf("%lld ",fz/fm);
61             }
62             printf("%lld/%lld
",fz-fz/fm*fm,fm);
63         }
64     }
65     return 0;
66 }
原文地址:https://www.cnblogs.com/Deribs4/p/4783580.html