Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 1081. Rational Sum

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

解答

#include <cstdio>

long long gcd(long long a, long long b)
{
	if (!a || !b) return a>b ? a : b;
	for (long long t; t = a % b; a = b, b = t);
	return b;
}

int main()
{
	long long n, a = 0, b = 1; scanf("%lld", &n);
	
	while (n--)
	{
		long long c, d; scanf("%lld/%lld", &c, &d);
		a = a * d + b * c, b = b * d;
		long long x = gcd(a>0 ? a : -a, b>0 ? b : -b); 
		a /= x, b /= x;
	}

	if (a/b && a%b) printf("%lld %lld/%lld\n", a/b, a%b, b);
	else if (a%b) printf("%lld/%lld\n", a%b, b);
	else printf("%lld\n", a/b);

	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论