NTT

namespace NTT {
    const int g = 3;
    int power(int x, int t) {
        int ret = 1;
        for(; t; t >>= 1, x = 1LL * x * x % P) 
            if(t & 1)
                ret = 1LL * ret * x % P;
        return ret;
    }
    void NTT(int *a, int len, int f) {     
        int n = 1 << len;
        for(int i = 0; i < n; ++i) {
            int t = 0;
            for(int j = 0; j < len; ++j) 
                if(i >> j & 1) 
                    t |= 1 << (len - j - 1); 
            if(i < t) swap(a[i], a[t]);
        }
        for(int l = 2; l <= n; l <<= 1) {
            int m = l >> 1;
            int w = power(g, f == 1 ? (P - 1) / l : (P - 1) - (P - 1) / l);
            for(int i = 0; i < n; i += l) {
                int t = 1;
                for(int k = 0; k < m; ++k, t = 1LL * t * w % P) {
                    int x = a[i + k], y = 1LL * t * a[i + m + k] % P;
                    a[i + k] = (x + y) % P;
                    a[i + k + m] = ((x - y) % P + P) % P;
                }
            }       
        }
        if(f == -1) {
            int inv = power(n, P - 2);
            for(int i = 0; i < n; ++i) a[i] = 1LL * a[i] * inv % P;
        }
    }
}

 

posted @ 2019-09-08 20:07  19992147  阅读(531)  评论(0编辑  收藏  举报