-
Notifications
You must be signed in to change notification settings - Fork 2
/
B1034.cpp
102 lines (91 loc) · 1.99 KB
/
B1034.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <cstdio>
#include <algorithm>
using namespace std;
struct Fraction{
long long up, down;
};
long long gcd(long long a, long long b){
if(b == 0) return a;
else return gcd(b, a%b);
}
Fraction reduction(Fraction result){
if(result.down < 0){
result.down = 0-result.down;
result.up = 0-result.up;
}
if(result.up == 0){
result.down = 1;
}else{
int d = gcd(abs(result.up), abs(result.down));
result.up /= d;
result.down /= d;
}
return result;
}
Fraction add(const Fraction &a, const Fraction &b){
Fraction result;
result.up = a.up * b.down + a.down * b.up;
result.down = a.down * b.down;
return result;
}
Fraction sub(const Fraction &a, const Fraction &b){
Fraction result;
result.up = a.up * b.down - a.down * b.up;
result.down = a.down * b.down;
return result;
}
Fraction multi(const Fraction &a, const Fraction &b){
Fraction result;
result.up = a.up * b.up;
result.down = a.down * b.down;
return result;
}
Fraction divide(const Fraction &a, const Fraction &b){
Fraction result;
result.up = a.up * b.down;
result.down = a.down * b.up;
return result;
}
void showResult(Fraction result){
result = reduction(result);
if(result.up < 0) printf("(");
if(result.down == 1) printf("%lld", result.up);
else if(result.down < abs(result.up)){
printf("%lld %lld/%lld", result.up/result.down, abs(result.up) % result.down, result.down);
}else{
printf("%lld/%lld", result.up, result.down);
}
if(result.up < 0) printf(")");
}
int main(){
Fraction a, b, result;
scanf("%lld/%lld %lld/%lld", &a.up, &a.down, &b.up, &b.down);
showResult(a);
printf(" + ");
showResult(b);
printf(" = ");
showResult(add(a, b));
printf("\n");
showResult(a);
printf(" - ");
showResult(b);
printf(" = ");
showResult(sub(a, b));
printf("\n");
showResult(a);
printf(" * ");
showResult(b);
printf(" = ");
showResult(multi(a, b));
printf("\n");
showResult(a);
printf(" / ");
showResult(b);
printf(" = ");
if(b.up != 0)
showResult(divide(a, b));
else
printf("Inf");
printf("\n");
return 0;
}