-
Notifications
You must be signed in to change notification settings - Fork 0
/
PAT-Advanced-1088.cpp
79 lines (69 loc) · 1.44 KB
/
PAT-Advanced-1088.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <sstream>
using namespace std;
long long gcd(long long a,long long b){
long long c;
while(b!=0){
c=a%b;
a=b;
b=c;
}
return a;
}
string solution(long long a,long long b){
stringstream ss;
bool sign=true;
if(a==0) return "0";
if(a<0&&b>0 || a>0&&b<0){
sign=false;
ss<<"(-";
a=abs(a);
b=abs(b);
}
long long d=gcd(a,b);
a/=d; b/=d;
if(a/b!=0) ss<<a/b;
if(a%b!=0){
if(a/b!=0) ss<<" ";
ss<<a%b<<"/"<<b;
}
if(!sign) ss<<")";
return ss.str();
}
int main(){
string str_1,str_2;
cin>>str_1>>str_2;
long long a1,b1,a2,b2,a3,b3;
long long index1=str_1.find('/'),index2=str_2.find('/');
a1=atoi(str_1.substr(0,index1).c_str());
b1=atoi(str_1.substr(index1+1,str_1.length()-index1-1).c_str());
a2=atoi(str_2.substr(0,index2).c_str());
b2=atoi(str_2.substr(index2+1,str_2.length()-index2-1).c_str());
// 化为最简
string num1,num2,ans;
num1=solution(a1,b1);
num2=solution(a2,b2);
// 加法
a3=a1*b2+a2*b1;
b3=b1*b2;
ans=solution(a3,b3);
cout<<num1<<" + "<<num2<<" = "<<ans<<endl;
// 减法
a3=a1*b2-a2*b1;
b3=b1*b2;
ans=solution(a3,b3);
cout<<num1<<" - "<<num2<<" = "<<ans<<endl;
// 乘法
a3=a1*a2;
b3=b1*b2;
ans=solution(a3,b3);
cout<<num1<<" * "<<num2<<" = "<<ans<<endl;
// 除法
if(a2==0 || b2==0) ans="Inf";
else{
a3=a1*b2;
b3=b1*a2;
ans=solution(a3,b3);
}
cout<<num1<<" / "<<num2<<" = "<<ans<<endl;
}