-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dora Learns Multiplication.cpp
87 lines (77 loc) · 2.12 KB
/
Dora Learns Multiplication.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
// Dora Learns Multiplication
#include <iostream>
#include <vector>
#include <cmath>
#include <complex>
using namespace std;
typedef complex<double> base;
void fft(vector<base> &a, bool invert) {
int n = a.size();
for (int i = 1, j = 0; i < n; ++i) {
int bit = n >> 1;
for (; j & bit; bit >>= 1)
j ^= bit;
j ^= bit;
if (i < j)
swap(a[i], a[j]);
}
for (int len = 2; len <= n; len <<= 1) {
double ang = 2 * M_PI / len * (invert ? -1 : 1);
base wlen(cos(ang), sin(ang));
for (int i = 0; i < n; i += len) {
base w(1);
for (int j = 0; j < len / 2; ++j) {
base u = a[i+j], v = a[i+j+len/2] * w;
a[i+j] = u + v;
a[i+j+len/2] = u - v;
w *= wlen;
}
}
}
if (invert)
for (int i = 0; i < n; ++i)
a[i] /= n;
}
vector<int> multiply(const vector<int> &a, const vector<int> &b) {
vector<base> fa(a.begin(), a.end()), fb(b.begin(), b.end());
int n = 1;
while (n < max(a.size(), b.size()))
n <<= 1;
n <<= 1;
fa.resize(n); fb.resize(n);
fft(fa, false); fft(fb, false);
for (int i = 0; i < n; ++i)
fa[i] *= fb[i];
fft(fa, true);
vector<int> result(n);
for (int i = 0; i < n; ++i)
result[i] = int(fa[i].real() + 0.5);
return result;
}
int main() {
int t;
cin >> t;
while (t--) {
string s1, s2;
cin >> s1 >> s2;
vector<int> a(s1.size()), b(s2.size());
for (int i = 0; i < s1.size(); ++i)
a[i] = s1[s1.size() - 1 - i] - '0';
for (int i = 0; i < s2.size(); ++i)
b[i] = s2[s2.size() - 1 - i] - '0';
vector<int> res = multiply(a, b);
int carry = 0;
for (int i = 0; i < res.size(); ++i) {
res[i] += carry;
carry = res[i] / 10;
res[i] %= 10;
}
int idx = res.size() - 1;
while (idx > 0 && res[idx] == 0)
idx--;
for (int i = idx; i >= 0; --i)
cout << res[i];
cout << "\n";
}
return 0;
}