PAT1081 Rational Sum (20)(gcd)

题意:

给出一些分数,要求以分数的形式输出它们的和

思路:

这题就是分别对分子和分母进行处理,中间有个点过不去因为分母过大超过范围,所以中间处理的时候要求出最大公约数,顺便我辗转相除法也忘了,复习一下。

#include<iostream>
#include<vector>
#include<cstdio>
#include<string>
#include<map>
#include<cmath>
#include<set>
#include<queue>
#include<functional>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 150;

long long gcd(long long a, long long b) {
	return b == 0 ? abs(a) : gcd(b, a%b);
}

int main() {
	int n;
	scanf("%d", &n);
	long long a, b, suma = 0, sumb = 1,gcdvalue;
	for (int i = 0; i < n; i++) {
		scanf("%lld/%lld", &a, &b);
		gcdvalue = gcd(a, b);
		a /= gcdvalue;
		b /= gcdvalue;
		suma = a*sumb + b*suma;
		sumb = b*sumb;
		gcdvalue = gcd(suma, sumb);
		suma /= gcdvalue;
		sumb /= gcdvalue;
	}
	if (suma == 0) {
		printf("0");
		return 0;
	}
	long long integer = suma / sumb;
	long long mod = suma%sumb;
	if (integer != 0 && mod != 0) {
		printf("%lld %lld/%lld", integer, mod, sumb);
	} else if (integer == 0) {
		printf("%lld/%lld", mod, sumb);
	} else {
		printf("%lld", integer);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/seasonjoe/article/details/80683597