Advertisement
Guest User

Untitled

a guest
May 30th, 2018
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. // FFT with complex:
  2. // Don’t use for long long values
  3. // Except for some special cases
  4. // Precalc roots of -1
  5. typedef complex<double> base;
  6. const int LEN  = 1<<20; // max length, power of 2
  7. base PW[LEN];           // LEN-th roots of -1
  8. void fft(vector<base>& a, bool invert)
  9. {
  10.     int lg = 0;
  11.     while((1<<lg) < SZ(a)) lg++;
  12.     FOR (i, 0, SZ(a))
  13.     {
  14.         int x=0;
  15.         FOR (j, 0, lg)
  16.             x |= ((i>>j)&1)<<(lg-j-1);
  17.         if(i<x)
  18.             swap(a[i], a[x]);
  19.     }
  20.     for (int len = 2; len <= SZ(a); len *= 2)
  21.     {
  22.         int diff = LEN / len;
  23.         if (invert) diff = LEN - diff;
  24.         for (int i = 0; i < SZ(a); i += len)
  25.         {
  26.             int pos = 0;
  27.             FOR (j, 0, len/2)
  28.             {
  29.                 base v = a[i+j];
  30.                 base u = a[i+j+len/2] * PW[pos];
  31.  
  32.                 a[i+j] = v + u;
  33.                 a[i+j+len/2] = v - u;
  34.  
  35.                 pos += diff;
  36.                 if (pos >= LEN) pos -= LEN;
  37.             }
  38.         }
  39.     }
  40.     if (invert)
  41.         FOR (i, 0, SZ(a))
  42.             a[i] /= SZ(a);
  43. }
  44. void initFFT()
  45. {
  46.     double angle = 2 * PI / LEN;
  47.     FOR (i, 0, LEN)
  48.     {
  49.         double ca = angle * i;
  50.         PW[i] = base(cos(ca), sin(ca));
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement