1081 Rational Sum (20 分)

本文介绍了一个算法,用于计算多个有理数之和,并将其化简为最简形式。输入包括一系列正负有理数,输出为化简后的整数部分及真分数部分。

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

AC代码

#include <iostream>
using namespace std;
long int GCD(long int x, long int y);	//得到x和y的最大公约数
long int LCM(long int x, long int y);	//得到x和y的最小公倍数
int main() {
	int N;
	cin >> N;
	int Num[201];
	int Z = 0;   //积累整数部分
	for (int i = 0; i < 2 * N; i += 2)	//得到所有分数的分子与分母
		scanf("%d/%d", &Num[i], &Num[i + 1]);
	long int a1, b1, a2, b2;
	a1 = Num[0];
	b1 = Num[1];
	long int Tmp = GCD(a1, b1);
	a1 /= Tmp;
	b1 /= Tmp;	 //实现自身化简
	for (int i = 2; i < 2 * N; i += 2) {
		a2 = Num[i];
		b2 = Num[i + 1];
		long int Tmp1 = GCD(a2, b2);
		a2 /= Tmp1;
		b2 /= Tmp1;	 //实现待相加的分数的自身化简
		long int LCM1 = LCM(b1, b2);	//求两个分数分母的最小公倍数
		long int Tmpa1 = a1*(LCM1 / b1) + a2*(LCM1 / b2);	//得到相加后未处理的分子
		long int GCD1 = GCD(Tmpa1, LCM1);
		a1 = Tmpa1 / GCD1;
		b1 = LCM1 / GCD1;	//得到化简完毕的分数
		if (b1 == 1) { Z += a1; a1 = 0; }	//得到整数的情况
		if (a1 > b1) { Z += (a1 / b1); a1 = a1 % b1; }	//将假分数化为整数和真分数
	}
	int flag = 0;
	if (Z) { cout << Z; flag = 1; }
	if (a1) {
		if (flag) cout << ' ';
		cout << a1 << '/' << b1 << endl;
	}
	if (Z == 0 && a1 == 0) cout << '0';	  //确保如果所有结果都为零时正常输出结果
	return 0;
}
long int LCM(long int x, long int y) {
	return x*y/GCD(x, y);
}
long int GCD(long int x, long int y){
	return y == 0 ? x : GCD(y, x%y);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值