1081. 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

求若干个分数的和,以带分数或分数的形式输出。这里的关键是约分,约分需要求最大公约数,用辗转相除法,要注意其中一个数是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);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值