您的位置:首页 > 其它

1081. Rational Sum (20)

2016-07-24 14:28 344 查看
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


求若干个分数的和,以带分数或分数的形式输出。这里的关键是约分,约分需要求最大公约数,用辗转相除法,要注意其中一个数是0的情况,这种情况设定公约数为1。先设答案为0/1(分数用分子和分母表示),然后将后面输入的分数(以字符串形式输入再做处理,求出分子和分母且保存好符号)逐个加在答案上,然后将答案约分。最后将得到的答案输出。输出注意如果是真分数不需要输出整数部分,如果分数部分的分子为0不需要输出分数部分,如果结果为0就输出0,其余情况都是带分数的形式。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;

long long get_GCM(int n,int m)
{
if(n<m) swap(n,m);
if(m==0) return 1;
long long r=n%m;
while(r!=0)
{
n=m;
m=r;
r=n%m;
}
return m;
}

int main()
{
int n;
cin>>n;
long long num=0,den=1;
for(int i=0;i<n;i++)
{
string s;
cin>>s;
int start=0,sign=1,j,count=0;
if(s[0]=='-')
{
start++;
sign=-1;
}
for(j=start;j<s.size();j++)
{
if(s[j]=='/') break;
count++;
}
long long num1=sign*atoll(s.substr(start,count).c_str());
long long den1=atoll(s.substr(j+1).c_str());
num=num*den1+num1*den;
den=den*den1;

int sign1=1;
if(num<0)
{
sign1=-1;
num=-num;
}
long long gcm=get_GCM(num,den);
num=sign1*num/gcm;
den/=gcm;
//cout<<num<<" "<<den<<" "<<gcm<<endl;
}
long long a=num/den,b=num%den,c=den;
if(a==0&&b==0) printf("0");
else if(a==0) printf("%lld/%lld",b,c);
else if(b==0) printf("%lld",a);
else printf("%lld %lld/%lld",a,b,c);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  math