标签:
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
这题WA了好久,代码也写得比较乱,卡在LL这里(BASIC里面还有LL卡测试点)......
大致思路就是先通分,再约分,最后转化成一个真分式
//ll WA #include <bits/stdc++.h> #define LL long long using namespace std; void convert(LL a, LL b); int main(){ LL a1, b1, a2, b2; scanf("%lld/%lld%lld/%lld", &a1, &b1, &a2, &b2); //+ convert(a1, b1); printf(" + "); convert(a2, b2); printf(" = "); convert(a1*b2+a2*b1, b1*b2); printf("\n"); //- convert(a1, b1); printf(" - "); convert(a2, b2); printf(" = "); convert(a1*b2-a2*b1, b1*b2); printf("\n"); //* convert(a1, b1); printf(" * "); convert(a2, b2); printf(" = "); convert(a1*a2, b1*b2); printf("\n"); // / convert(a1, b1); printf(" / "); convert(a2, b2); printf(" = "); if(a2 == 0){ printf("Inf\n"); } else{ convert(a1*b2, a2*b1); printf("\n"); } return 0; } void convert(LL a, LL b){ if(a > 0 && b < 0){ a = -a; b = -b; } else if(a < 0 && b < 0){ a = -a; b = -b; } // a = b*k if(a % b == 0){ if(a < 0){ printf("(%lld)", a/b); } else{ printf("%lld", a/b); } return; } //otherwise //simplify for(int i = 2; i <= sqrt(max(a,b)); ++i){ while(a % i == 0 && b % i == 0){ a /= i; b /= i; } } if(a < 0){ //- if(a / b != 0){ printf("(%lld %lld/%lld)", a/b, (abs(a))%b, b); } else{ printf("(%lld/%lld)", a, b); } } else{ //+ if(a / b != 0){ printf("%lld %lld/%lld", a/b, a%b, b); } else{ printf("%lld/%lld", a, b); } } }
PAT-ADVANCED-1088-Rational Arithmetic
标签:
原文地址:http://www.cnblogs.com/capouis/p/4791035.html