NTT模板

时间:2023-03-08 18:36:09
NTT模板

NTT(快速数论变换)用到的各种素数及原根:

https://blog.csdn.net/hnust_xx/article/details/76572828

NTT多项式乘法模板

#include<cstdio>
#include<iostream>
#include<algorithm> using namespace std; typedef long long LL; const LL mod=; //119*2^23+1 g=3 const int N=(<<)+; const int g=; int rev[N]; LL a[N],b[N]; template<typename T>
void read(T &x)
{
x=; char c=getchar();
while(!isdigit(c)) c=getchar();
while(isdigit(c)) { x=x*+c-''; c=getchar(); }
} LL Pow(LL a,LL b)
{
LL res=;
for(;b;a=a*a%mod,b>>=)
if(b&) res=res*a%mod;
return res;
} void NTT(LL *a,int n,int f)
{
for(int i=;i<n;++i)
if(i<rev[i]) swap(a[i],a[rev[i]]);
for(int i=;i<n;i<<=)
{
LL wn=Pow(g,(mod-)/(i*));
if(f<) wn=Pow(wn,mod-);
for(int j=,p=i<<;j<n;j+=p)
{
LL w=;
for(int k=;k<i;++k,w=w*wn%mod)
{
int x=a[j+k],y=w*a[j+k+i]%mod;
a[j+k]=(x+y)%mod; a[j+k+i]=(x-y+mod)%mod;
}
}
}
if(f<)
{
LL inv=Pow(n,mod-);
for(int i=;i<n;++i) a[i]=a[i]*inv%mod;
}
} int main()
{
int nn,mm;
read(nn); read(mm);
for(int i=;i<=nn;++i) read(a[i]);
for(int i=;i<=mm;++i) read(b[i]);
int l=,len=nn+mm;
int n;
for(n=;n<=len;n<<=) l++;
for(int i=;i<n;++i) rev[i]=(rev[i>>]>>)|((i&)<<l-);
NTT(a,n,);
NTT(b,n,);
for(int i=;i<n;++i) a[i]=a[i]*b[i]%mod;
NTT(a,n,-);
for(int i=;i<=len;++i) printf("%lld ",a[i]);
}