和1081一样,又是一道牛客网通过PAT一个测点错误的题,可能就是有个特殊情况没有考虑到,暂时还没找到,待优化
#include <iostream>
#include <climits>
using namespace std;
struct Fraction{
long long integer;
long long up;
long long down;
};
long long gcd(long long a,long long b){
return !b ? a : gcd(b,a % b);
}
Fraction reduction(Fraction f){
if(f.up == 0){
f.down = 1;
f.integer = 0;
}else{
long long d = gcd(abs(f.up),abs(f.down));
f.up /= d;
f.down /= d;
f.integer = f.up / f.down;
if(f.up < 0 && f.integer != 0)
f.up = -f.up;
f.up = f.up % f.down;
}
return f;
}
Fraction add(Fraction a,Fraction b){
Fraction res;
res.up = a.up * b.down + b.up * a.down;
res.down = a.down * b.down;
return reduction(res);
}
Fraction minu(Fraction a,Fraction b){
Fraction res;
res.up = a.up * b.down - b.up * a.down;
res.down = a.down * b.down;
return reduction(res);
}
Fraction multiply(Fraction a,Fraction b){
Fraction res;
res.up = a.up * b.up;
res.down = a.down * b.down;
return reduction(res);
}
Fraction division(Fraction a,Fraction b){
Fraction res;
if(b.up == 0){
res.integer = INT_MAX;
return res;
}
res.up = abs(a.up * b.down);
res.down = abs(a.down * b.up);
if(a.up * b.up < 0)
res.up = -res.up;
return reduction(res);
}
void printFraction(Fraction f){
if(f.integer == INT_MAX){
printf("Inf");
return;
}
if(f.up == 0 && f.integer == 0){
printf("0");
return;
}
if(f.integer != 0){
if(f.up != 0){
if(f.integer < 0){
printf("(%lld %lld/%lld)",f.integer,f.up,f.down);
}else{
printf("%lld %lld/%lld",f.integer,f.up,f.down);
}
}
else{
if(f.integer < 0)
printf("(%lld)",f.integer);
else
printf("%lld",f.integer);
}
}else{
if(f.up < 0){
printf("(%lld/%lld)",f.up,f.down);
}else{
printf("%lld/%lld",f.up,f.down);
}
}
return;
}
int main(){
Fraction a,b;
scanf("%lld/%lld %lld/%lld",&a.up,&a.down,&b.up,&b.down);
a.integer = 0;
b.integer = 0;
Fraction res1 = add(a,b);
Fraction res2 = minu(a,b);
Fraction res3 = multiply(a,b);
Fraction res4 = division(a,b);
a = reduction(a);
b = reduction(b);
for(int i = 0;i < 4;i++){
printFraction(a);
switch(i){
case 0:
printf(" + ");
break;
case 1:
printf(" - ");
break;
case 2:
printf(" * ");
break;
case 3:
printf(" / ");
break;
}
printFraction(b);
printf(" = ");
switch(i){
case 0:
printFraction(res1);
printf("\n");
break;
case 1:
printFraction(res2);
printf("\n");
break;
case 2:
printFraction(res3);
printf("\n");
break;
case 3:
printFraction(res4);
break;
}
}
system("pause");
return 0;
}