-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP1303-FFT.cpp
More file actions
98 lines (83 loc) · 2.1 KB
/
P1303-FFT.cpp
File metadata and controls
98 lines (83 loc) · 2.1 KB
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
#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
struct Complex {
double x, y;
Complex(double x = 0, double y = 0) : x(x), y(y) {}
Complex operator+(const Complex & o) const {return Complex(x + o.x, y + o.y);}
Complex operator-(const Complex & o) const {return Complex(x - o.x, y - o.y);}
Complex operator*(const Complex & o) const {return Complex(x * o.x - y * o.y, x * o.y + y * o.x);}
};
void fft(vector<Complex> & 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 * PI / len * (invert ? -1 : 1);
Complex wlen(cos(ang), sin(ang));
for (int i = 0; i < n; i += len)
{
Complex w(1);
for (int j = 0; j < len / 2; j++)
{
Complex u = a[i + j], v = a[i + j + len / 2] * w;
a[i + j] = u + v;
a[i + j + len / 2] = u - v;
w = w * wlen;
}
}
}
if (invert)
for (auto&x : a)
x.x /= n;
}
string multiply(string a, string b)
{
if (a == "0" || b == "0") return "0";
while (a.size() > 1 && a[0] == '0') a.erase(a.begin());
while (b.size() > 1 && b[0] == '0') b.erase(b.begin());
vector<Complex> fa(a.size()), fb(b.size());
for (int i = 0; i < a.size(); i++) fa[i] = Complex(a[a.size() - 1 - i] - '0', 0);
for (int i = 0; i < b.size(); i++) fb[i] = Complex(b[b.size() - 1 - i] - '0', 0);
int n = 1;
while (n < (int)(fa.size() + fb.size())) n <<= 1;
fa.resize(n); fb.resize(n);
fft(fa, false);
fft(fb, false);
for (int i = 0; i < n; i++) fa[i] = fa[i] * fb[i];
fft(fa, true);
vector<int> res(n);
for (int i = 0; i < n; i++)
res[i] = round(fa[i].x);
int carry = 0;
for (int i = 0; i < n; i++)
{
res[i] += carry;
carry = res[i] / 10;
res[i] %= 10;
}
while (carry)
{
res.push_back(carry % 10);
carry /= 10;
}
while (res.size() > 1 && res.back() == 0) res.pop_back();
string ans;
for (int i = res.size() - 1; i >= 0; i--)
ans += char(res[i] + '0');
return ans;
}
int main()
{
string a, b, c;
cin >> a >> b;
cout << multiply(a, b) << endl;
return 0;
}