For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
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.
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.
2/3 -4/2
2/3 + (-2) = (-1 1/3) 2/3 - (-2) = 2 2/3 2/3 * (-2) = (-1 1/3) 2/3 / (-2) = (-1/3)
5/3 0/6
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<iostream> using namespace std; struct Fraction { long long int up,down; }num[110]; int gcd(long long int a,long long int b) { if(b==0) return a; else return gcd(b,a%b); } long long int abs1(long long int a) { if(a<0) return -a; else return a; } Fraction reduction(Fraction a) { if(a.down<0) { a.up=-a.up; a.down=-a.down; } if(a.up==0) a.down=1; else { int d=gcd(abs1(a.up),abs1(a.down)); a.up/=d; a.down/=d; } return a; } Fraction add(Fraction a,Fraction b) { Fraction result; result.up=a.up*b.down+b.up*a.down; result.down=a.down*b.down; return result; } Fraction sub(Fraction a,Fraction b) { Fraction result; result.up=a.up*b.down-b.up*a.down; result.down=a.down*b.down; return result; } Fraction mul(Fraction a,Fraction b) { Fraction result; result.up=a.up*b.up; result.down=a.down*b.down; return result; } Fraction div(Fraction a,Fraction b) { Fraction result; result.up=a.up*b.down; result.down=a.down*b.up; return result; } void show(Fraction sum) { if(sum.up<0) printf("("); if(abs1(sum.up)>sum.down) { printf("%lld",sum.up/sum.down); if(abs1(sum.up)%sum.down) printf(" %lld/%lld",abs1(sum.up)%sum.down,sum.down); } else if(sum.down==1) printf("%lld",sum.up); else printf("%lld/%lld",sum.up,sum.down); if(sum.up<0) printf(")"); } int main() { Fraction a,b,c; int flag=0; char op[4]={'+','-','*','/'}; scanf("%lld/%lld %lld/%lld",&a.up,&a.down,&b.up,&b.down); a=reduction(a); b=reduction(b); for(int i=0;i<4;i++) { switch(i){ case 0:c=add(a,b);break; case 1:c=sub(a,b);break; case 2:c=mul(a,b);break; case 3:c=div(a,b); if(b.up==0) flag=1; } c=reduction(c); show(a); printf(" %c ",op[i]); show(b); printf(" = "); if(flag==0) show(c); else printf("Inf"); printf("\n"); } return 0; }