PAT (Advanced) 1081. Rational Sum (20)

#include <iostream>

using namespace std;

long long gcd(long long a, long long b)
{
	long long r;
	while (b > 0)
	{
		r = a % b;
		a = b;
		b = r;
	}
	return a;
}

long long lcm(long long a, long long b)
{
	return a / gcd(a, b) * b;
}

int main()
{
	int n;
	cin >> n;
	long long a1 = 0, b1 = 1, a2, b2;
	long long multiple, factor;

	for (int i = 0; i < n; i++)
	{
		cin >> a2;
		getchar();
		cin >> b2;

		multiple = lcm(b1, b2);
		a1 *= multiple / b1;
		a2 *= multiple / b2;
		a1 += a2;
		b1 = multiple;

		factor = gcd(a1, b1);
		a1 /= factor;
		b1 /= factor;
		if (a1 == 0)
			b1 = 1;
	}
	if (a1 == 0)
		cout << 0;
	else
	{
		if (a1 / b1 != 0)
		{
			cout << a1 / b1;
			a1 %= b1;
			if (a1 != 0)
				cout << " ";
		}
		if (a1 != 0)
			cout << a1 << "/" << b1;
	}
	cout << endl;
}

你可能感兴趣的:(PAT (Advanced) 1081. Rational Sum (20))