Advertisement
Guest User

Untitled

a guest
May 30th, 2018
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. // FFT with modulo:
  2. // GEN ^ LEN == 1 mod BASE
  3. // GEN ^ (LEN / 2) != 1 mod BASE
  4. // for prime modulo c2^k+1 generator for len 2^k exists always
  5. const int LEN = 1<<20;    // max length, power of 2
  6. const int BASE = 7340033; // modulo
  7. const int GEN = 5;        // generator
  8. int PW[LEN];              // powers of generator
  9. void fft(vector<int>& a, bool invert)
  10. {
  11.     int lg = 0;
  12.     while((1<<lg) < SZ(a)) lg++;
  13.        
  14.     FOR (i, 0, SZ(a))
  15.     {
  16.         int x=0;
  17.         FOR (j, 0, lg)
  18.             x |= ((i>>j)&1)<<(lg-j-1);
  19.         if(i<x)
  20.             swap(a[i], a[x]);      
  21.     }
  22.  
  23.     for (int len = 2; len <= SZ(a); len *= 2)
  24.     {
  25.         int diff = LEN / len;
  26.         if (invert) diff = LEN - diff;
  27.         for (int i = 0; i < SZ(a); i += len)
  28.         {
  29.             int pos = 0;
  30.             FOR (j, 0, len/2)
  31.             {
  32.                 int w = PW[pos];
  33.  
  34.                 int v = a[i+j];
  35.                 int u = (a[i+j+len/2] * (LL) w) % BASE;
  36.  
  37.                 int t = v + u;
  38.                 if (t >= BASE) t -= BASE;
  39.                 a[i+j] = t;
  40.  
  41.                 t = v - u;
  42.                 if (t < 0) t += BASE;
  43.                 a[i+j+len/2] = t;
  44.  
  45.                 pos += diff;
  46.                 if (pos >= LEN) pos -= LEN;
  47.             }
  48.         }
  49.     }
  50.  
  51.     if (invert)
  52.     {
  53.         int m = inv(SZ(a), BASE);
  54.         FOR (i, 0, SZ(a))
  55.             a[i] = (a[i] * (LL)m) % BASE;
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement