-
Notifications
You must be signed in to change notification settings - Fork 3
/
fraction.cpp
91 lines (79 loc) · 1.29 KB
/
fraction.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
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll gcd(ll a, ll b) {
if (b == 0) return a;
return gcd(b, a % b);
}
struct rat {
ll p, q;
rat() : p(1), q(1) {}
rat(ll p, ll q) {
if (q < 0) {
p *= -1;
q *= -1;
}
ll k = gcd(abs(p), q);
this->p = p / k;
this->q = q / k;
}
rat operator+(const rat &o) {
return rat(
p * o.q + o.p * q,
q * o.q
);
}
rat operator-(const rat &o) {
return rat(
p * o.q - o.p * q,
q * o.q
);
}
rat operator*(const rat &o) {
return rat(
p * o.p,
q * o.q
);
}
rat operator/(const rat &o) {
return rat(
p * o.q,
q * o.p
);
}
rat flip() {
return rat(q, p);
}
};
void display(rat n) {
ll cur = n.p / n.q;
while (true) {
cout << cur << " ";
n = n - rat(cur, 1);
if (!n.p) break;
n = n.flip();
cur = n.p / n.q;
}
cout << endl;
}
rat build(int n) {
rat res(0, 1);
vector<ll> V(n);
for (auto &v : V) cin >> v;
for (ll i = n - 1; i >= 0; --i) {
res = res + rat(V[i], 1);
res = res.flip();
}
return res.flip();
}
int main() {
int n, m;
cin >> n >> m;
rat A = build(n);
rat B = build(m);
display(A + B);
display(A - B);
display(A * B);
display(A / B);
return 0;
}