Skip to content

Commit

Permalink
Faster Polynomial multiplication by combining two FFTs
Browse files Browse the repository at this point in the history
  • Loading branch information
jakobkogler committed Jul 30, 2020
1 parent e4b711e commit fcb7444
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions Math/FFT.h
Original file line number Diff line number Diff line change
Expand Up @@ -91,28 +91,28 @@ class FFT {
}
}

void multiply(vcd & fa, vcd & fb) {
int result_size = fa.size() + fb.size() - 1;
int size = 1 << get_lg(result_size);
fa.resize(size);
fb.resize(size);

fft(fa, false);
fft(fb, false);
for (int i = 0; i < size; i++)
fa[i] *= fb[i];
fft(fa, true);

fa.resize(result_size);
}

template <typename T>
std::vector<T> multiply(std::vector<T> const& a, std::vector<T> const& b) {
int result_size = a.size() + b.size() - 1;
vcd fa(a.begin(), a.end()), fb(b.begin(), b.end());
multiply(fa, fb);
fa.resize(result_size);
return convert_back<T>(fa);
int size = 1 << get_lg(result_size);
vcd f(size, {0, 0});
int sz = std::max(a.size(), b.size());
for (int i = 0; i < sz; i++) {
const T& A = i < a.size() ? a[i] : 0;
const T& B = i < b.size() ? b[i] : 0;
f[i] = {(double)A, (double)B};
}

fft(f, false);
vcd h(size);
cd factor(0, -0.25);
for (int i = 0; i < size; i++) {
int j = (size - i) & (size - 1);
h[i] = (f[i]*f[i] - std::conj(f[j]*f[j])) * factor;
}
fft(h, true);
h.resize(result_size);
return convert_back<T>(h);
}

template <typename T>
Expand Down

0 comments on commit fcb7444

Please sign in to comment.