#include #include #include #include using namespace std; vector> fft(const vector> &a, bool inverse) { const int n = a.size(); if (n == 1) return a; complex w = 1.0; complex w_n; if (inverse) { w_n = exp(1i * (-2.0) * M_PI / (double) n); } else { w_n = exp(1i * 2.0 * M_PI / (double) n); } // Delimo vector> a_0(n / 2); vector> a_1(n / 2); for (int i = 0; i < n / 2; i++) { a_0[i] = a[2*i]; a_1[i] = a[2*i + 1]; } // Rekurzija vector> y_0 = fft(a_0, inverse); vector> y_1 = fft(a_1, inverse); // Objedinjujemo vector> y (n); for (int k = 0; k < n / 2; k++) { y[k] = y_0[k] + w * y_1[k]; y[k + n / 2] = y_0[k] - w * y_1[k]; w *= w_n; } return y; } vector> convolution(const vector> &a, const vector> &b) { const int n = a.size(); vector> x = fft(a, false); vector> y = fft(b, false); for (int i = 0; i < n; i++) { x[i] *= y[i]; } vector> c = fft(x, true); for (int i = 0; i < n; i++) { c[i] /= (double) n; } return c; } void print_poly(const vector> &a) { const int n = a.size(); for (int i = 0; i < n - 1; i++) { cout << real(a[i]) << "*x^" << i << " + "; } cout << real(a[n - 1]) << "*x^" << n - 1 << endl; } int main(void) { vector> a = {1., 2., 1., 1., 0., 0., 0., 0.}; vector> b = {3., 2., 1., 2., 0., 0., 0., 0.}; print_poly(a); print_poly(b); vector> c = convolution(a, b); print_poly(c); return 0; }