-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathNTT.cpp
More file actions
59 lines (53 loc) · 1.72 KB
/
NTT.cpp
File metadata and controls
59 lines (53 loc) · 1.72 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
// If p=c.2^k+1, then we need 2^k th root of unity
// root= not generator, rather g^c , root of unity, root_1 is its inverse wrt mod, root_pw means 2^k
// inverse(n,mod) is a function for modular inverse\
// for fft with arbitrary remainder, break coefficients into modulo sqrt(M), dont use CRT
const int mod = 7340033;
const int root = 5;
const int root_1 = 4404020;
const int root_pw = 1 << 20;
void fft(vector<int> & 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) {
int wlen = invert ? root_1 : root;
for (int i = len; i < root_pw; i <<= 1)
wlen = (int)(1LL * wlen * wlen % mod);
for (int i = 0; i < n; i += len) {
int w = 1;
for (int j = 0; j < len / 2; j++) {
int u = a[i+j], v = (int)(1LL * a[i+j+len/2] * w % mod);
a[i+j] = u + v < mod ? u + v : u + v - mod;
a[i+j+len/2] = u - v >= 0 ? u - v : u - v + mod;
w = (int)(1LL * w * wlen % mod);
}
}
}
if (invert) {
int n_1 = inverse(n, mod);
for (int & x : a)
x = (int)(1LL * x * n_1 % mod);
}
}
vector<int> multiply(vector<int> const& a, vector<int> const& b) {
vector<int> fa(a),fb(b) ;
int n = 1;
while (n < a.size() + b.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]*1LL*fb[i])%mod;
fft(fa, true);
fa.resize(a.size()+b.size()-1) ;
return fa;
}