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
注意:
1、用好辗转相除法,这一题跟1088比真是小巫见大巫。。。
2、先约分再相加,避免溢出。

代码:
//1081
#include<iostream>
using namespace std;

void reduct(long &a,long &b)
{//calculate the irreducible fraction of this fraction.
	if(a==0)
	{
		b=1;
		return;
	}
	int x=a,y=b;
	while(x%y!=0)
	{//Euclidean algorithm
		int t=x%y;
		x=y;
		y=t;
	}
	a/=y;
	b/=y;
}

int main()
{
	int n;
	scanf("%d",&n);
	long a,b;
	scanf("%ld/%ld",&a,&b);
	reduct(a,b);
	for(int i=1;i<n;++i)
	{
		long a0,b0;
		scanf("%ld/%ld",&a0,&b0);
		reduct(a0,b0);
		a = a*b0 + a0*b;
		b = b*b0;
		reduct(a,b);
	}
	if(a<0)
	{
		printf("-");
		a = -a;
	}
	if(b==1)//it has only the integer part
		printf("%d\n",a/b);
	else if(a<b)//it has only the fractional part
		printf("%d/%d\n",a%b,b);
	else
		printf("%d %d/%d\n",a/b,a%b,b);
	return 0;
}


你可能感兴趣的:(考试,pat,浙江大学)