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

PAT 1088. Rational Arithmetic

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.

Input Specification

Each input file contains one test case, which gives in one line the two rational numbers in the format "a1/b1 a2/b2". The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.

Output Specification

For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is "number1 operator number2 = result". Notice that all the rational numbers must be in their simplest form "k a/b", where k is the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output "Inf" as the result. It is guaranteed that all the output integers are in the range of long int.

Sample Input 1

2/3 -4/2

Sample Output 1

2/3 + (-2) = (-1 1/3)
2/3 – (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)

Sample Input 2

5/3 0/6

Sample Output 2

1 2/3 + 0 = 1 2/3
1 2/3 – 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf

解答

#include <cstdio>

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

void simplify(long long &a, long long &b)
{
	long long x = gcd(a<0 ? -a : a, b);
	a /= x, b /= x; 
}

void f(long long a, long long b)
{
	if (b == 0) { printf("Inf"); return; }

	if (b < 0) a = -a, b = -b;
	simplify(a, b);
	bool flag = 0;
	if (a < 0) a = -a, flag = 1;

	if (flag) printf("(-");
	if (a % b == 0) printf("%lld", a / b);
	else if (a < b) printf("%lld/%lld", a, b);
	else printf("%lld %lld/%lld", a / b, a % b, b);
	if (flag) printf(")");
}

int main()
{
	long long a1, b1, a2, b2; scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2);
	f(a1, b1); printf(" + "); f(a2, b2); printf(" = "); f(a1*b2+a2*b1, b1*b2); printf("\n");
	f(a1, b1); printf(" - "); f(a2, b2); printf(" = "); f(a1*b2-a2*b1, b1*b2); printf("\n");
	f(a1, b1); printf(" * "); f(a2, b2); printf(" = "); f(a1*a2, b1*b2); printf("\n");
	f(a1, b1); printf(" / "); f(a2, b2); printf(" = "); f(a1*b2, a2*b1); printf("\n");
	return 0;
}
上一篇: 下一篇:

我的博客

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

站内搜索

最新评论