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/2Sample 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/6Sample 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
//1088
#include<iostream>
using namespace std;
void reduct(long &a,long &b)
{//calculate the irreducible fraction of this fraction.
if(a==0)
{
b=1;
return;
}
else if(b==0)
return;
if(a<0&&b<0)
a=-a,b=-b;
long x=a,y=b;
if(a<0&&b>0)
x=-a;
//make sure that only numerator can be negative
if(b<0&&a>0)
y=b=-b,a=-a;
while(x%y!=0)
{
long z=x%y;
x=y;
y=z;
}
a/=y;
b/=y;
}
int main()
{
long a1,b1,a2,b2;
cin>>a1;getchar();cin>>b1;
cin>>a2;getchar();cin>>b2;
reduct(a1,b1);
reduct(a2,b2);
char arith[4]={'+','-','*','/'};
long a3[4],b3[4];
//sum
a3[0]=a1*b2+a2*b1;
b3[0]=b1*b2;
//difference
a3[1]=a1*b2-a2*b1;
b3[1]=b1*b2;
//product
a3[2]=a1*a2;
b3[2]=b1*b2;
//quotient
a3[3]=a1*b2;
b3[3]=a2*b1;
for(int i=0;i<4;++i)
{
reduct(a3[i],b3[i]);
long a[3]={a1,a2,a3[i]};
long b[3]={b1,b2,b3[i]};
for(int j=0;j<3;++j)
{
if(b[j]==0)
cout<<"Inf";
else if(a[j]==0)
cout<<'0';
else
{
int neg=0;//negative number flag
if(a[j]<0)
{//negative fraction
neg=1;
a[j]=-a[j];
cout<<"(-";
}
if(a[j]%b[j]==0)//only integer part
cout<<a[j]/b[j];
else if(a[j]<b[j])//only fraction part
cout<<a[j]<<'/'<<b[j];
else//other situations
cout<<a[j]/b[j]<<' '<<a[j]%b[j]<<'/'<<b[j];
if(neg)
cout<<')';
}
if(j==0)
cout<<' '<<arith[i]<<' ';
if(j==1)
cout<<" = ";
}
cout<<endl;
}
return 0;
}