-
Notifications
You must be signed in to change notification settings - Fork 3
/
fft.cpp
69 lines (60 loc) · 1.89 KB
/
fft.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
typedef long double DOUBLE;
typedef complex<DOUBLE> COMPLEX;
typedef vector<DOUBLE> VD;
typedef vector<COMPLEX> VC;
struct FFT {
VC A;
int n, L;
int ReverseBits(int k) {
int ret = 0;
for (int i = 0; i < L; i++) {
ret = (ret << 1) | (k & 1);
k >>= 1;
}
return ret;
}
void BitReverseCopy(VC a) {
for (n = 1, L = 0; n < a.size(); n <<= 1, L++) ;
A.resize(n);
for (int k = 0; k < n; k++)
A[ReverseBits(k)] = a[k];
}
VC DFT(VC a, bool inverse) {
BitReverseCopy(a);
for (int s = 1; s <= L; s++) {
int m = 1 << s;
COMPLEX wm = exp(COMPLEX(0, 2.0 * M_PI / m));
if (inverse) wm = COMPLEX(1, 0) / wm;
for (int k = 0; k < n; k += m) {
COMPLEX w = 1;
for (int j = 0; j < m/2; j++) {
COMPLEX t = w * A[k + j + m/2];
COMPLEX u = A[k + j];
A[k + j] = u + t;
A[k + j + m/2] = u - t;
w = w * wm;
}
}
}
if (inverse) for (int i = 0; i < n; i++) A[i] /= n;
return A;
}
// c[k] = sum_{i=0}^k a[i] b[k-i]
VD Convolution(VD a, VD b) {
int L = 1;
while ((1 << L) < a.size()) L++;
while ((1 << L) < b.size()) L++;
int n = 1 << (L+1);
VC aa, bb;
for (size_t i = 0; i < n; i++) aa.push_back(i < a.size() ? COMPLEX(a[i], 0) : 0);
for (size_t i = 0; i < n; i++) bb.push_back(i < b.size() ? COMPLEX(b[i], 0) : 0);
VC AA = DFT(aa, false);
VC BB = DFT(bb, false);
VC CC;
for (size_t i = 0; i < AA.size(); i++) CC.push_back(AA[i] * BB[i]);
VC cc = DFT(CC, true);
VD c;
for (int i = 0; i < a.size() + b.size() - 1; i++) c.push_back(cc[i].real());
return c;
}
};