-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfft.cpp
49 lines (49 loc) · 1.17 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
typedef complex < double > base ;
#define PI 3.141592653589793l
void fft(vector<base> &a,bool invert){
int i,j,n=sz(a);
for(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);
base wlen(cos(ang),sin(ang));
for(i=0;i<n;i+=len){
base w(1);
for(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(i=0;i<n;++i){
a[i]/=n;
}
}
}
void multiply(const vector<int> &a,const vector<int> &b,vector <int> &res){
vector<base> fa(a.begin(),a.end()),fb(b.begin(),b.end());
size_t 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(size_t i=0;i<n;++i){
fa[i]*=fb[i];
}
fft(fa,true);
res.resize(n);
for(size_t i=0;i<n;++i){
res[i]=(int)(fa[i].real()+0.5);
}
}