2015-02-05
http://www.patest.cn/contests/pat-a-practise/1088
1 #include <iostream> 2 #include <cmath> 3 using namespace std; 4 typedef long long LL; 5 typedef struct Fraction{ 6 LL up,down; 7 }; 8 LL gcd(LL a,LL b){ 9 return b==0 ? a : gcd(b,a%b); 10 } 11 Fraction reduction(Fraction res){ 12 if(res.down<0){ 13 res.down=-res.down; 14 res.up=-res.up; 15 } 16 else if(res.up==0) 17 res.down==1; 18 else{ 19 LL d=gcd(abs(res.up),res.down); 20 res.up/=d; 21 res.down/=d; 22 } 23 return res; 24 } 25 Fraction add(Fraction a,Fraction b){ 26 Fraction res; 27 res.up=a.up*b.down+a.down*b.up; 28 res.down=a.down*b.down; 29 return reduction(res); 30 } 31 Fraction sub(Fraction a,Fraction b){ 32 Fraction res; 33 res.up=a.up*b.down-a.down*b.up; 34 res.down=a.down*b.down; 35 return reduction(res); 36 } 37 Fraction multi(Fraction a,Fraction b){ 38 Fraction res; 39 res.up=a.up*b.up; 40 res.down=a.down*b.down; 41 return reduction(res); 42 } 43 Fraction divide(Fraction a,Fraction b){ 44 Fraction res; 45 res.up=a.up*b.down; 46 res.down=a.down*b.up; 47 return reduction(res); 48 } 49 void showFraction(Fraction res){ 50 res=reduction(res); 51 if(res.up<0) 52 printf("("); 53 if(res.down==1) 54 printf("%lld",res.up); 55 else if(res.up==0) 56 printf("0"); 57 else if(abs(res.up)>res.down){ 58 printf("%lld %lld/%lld",res.up/res.down,abs(res.up)%res.down,res.down); 59 } 60 else{ 61 printf("%lld/%lld",res.up,res.down); 62 } 63 if(res.up<0) 64 printf(")"); 65 } 66 void output(Fraction a,Fraction b,char ch){ 67 showFraction(a); 68 printf(" %c ",ch); 69 showFraction(b); 70 printf(" = "); 71 switch(ch){ 72 case '+': 73 showFraction(add(a,b)); 74 break; 75 case '-': 76 showFraction(sub(a,b)); 77 break; 78 case '*': 79 showFraction(multi(a,b)); 80 break; 81 case '/': 82 if(b.up==0) 83 printf("Inf"); 84 else 85 showFraction(divide(a,b)); 86 break; 87 default: 88 printf("error"); 89 break; 90 } 91 printf("\n"); 92 } 93 int main() 94 { 95 Fraction a,b,ans; 96 while(scanf("%lld/%lld %lld/%lld",&a.up,&a.down,&b.up,&b.down)!=EOF){ 97 a=reduction(a); 98 b=reduction(b); 99 output(a,b,'+'); 100 output(a,b,'-'); 101 output(a,b,'*'); 102 output(a,b,'/'); 103 } 104 return 0; 105 }