forked from algorithmica-org/implementations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfft.cpp
52 lines (46 loc) · 1.08 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
#include <bits/stdc++.h>
using namespace std;
typedef complex<double> CC;
double pi = acos(-1);
void fft(vector<CC> &a, int k = 1){
int n = (int) a.size();
if(n == 1) return;
vector<CC> a0(n/2), a1(n/2);
for(int i = 0; i < n/2; i++){
a0[i] = a[2*i];
a1[i] = a[2*i+1];
}
fft(a0, k);
fft(a1, k);
double ang = k*2*pi/n;
CC w(1), wn(cos(ang), sin(ang));
for(int i = 0; i < n/2; i++){
a[i] = a0[i] + w*a1[i];
a[i+n/2] = a0[i] - w*a1[i];
w *= wn;
}
}
vector<double> multiply(vector<double> a, vector<double> b){
size_t n = 1;
while(n < max(a.size(), b.size())) n *= 2;
n *= 2;
vector<CC> _a(a.begin(), a.end()), _b(b.begin(), b.end());
_a.resize(n), _b.resize(n);
fft(_a);
fft(_b);
for(size_t i = 0; i < n; i++)
_a[i] *= _b[i];
fft(_a, -1);
for(size_t i = 0; i < n; i++)
_a[i] = complex<double> (_a[i].real()/(double)n, _a[i].imag());
vector<double> ans(n);
for(size_t i = 0; i < n; i++)
ans[i] = _a[i].real();
return ans;
}
int main(){
vector<double> a = {1, 1, 2, 3}, b = {8, 2, 2, 5};
vector<double> c = multiply(a, b);
for(double x : c)
cout << x << " ";
}