洛谷3811
先用n!p-2求出n!的乘法逆元
因为有(i-1)!-1=i!-1*i (mod p),于是我们可以O(n)求出i!-1
再用i!-1*(i-1)!=i-1 (mod p)即是答案
1 #include<iostream> 2 #include<cstring> 3 #include<cstdlib> 4 #include<cstdio> 5 #include<cmath> 6 #include<algorithm> 7 using namespace std; 8 const int maxn=3000010, inf=1e9; 9 int n, p; 10 int fac[maxn], inv[maxn]; 11 inline void read(int &k){ 12 int f=1; k=0; char c=getchar(); 13 while(c<'0' || c>'9') c=='-'&&(f=-1), c=getchar(); 14 while(c<='9' && c>='0') k=k*10+c-'0', c=getchar(); 15 k*=f; 16 } 17 inline int power(int a, int b){ 18 int ans=1; 19 for(;b;b>>=1, a=1ll*a*a%p) 20 if(b&1) ans=1ll*ans*a%p; 21 return ans; 22 } 23 int main(){ 24 read(n); read(p); 25 fac[0]=1; for(int i=1;i<=n;i++) fac[i]=1ll*fac[i-1]*i%p; 26 inv[n]=power(fac[n], p-2); 27 for(int i=n;i;i--) inv[i-1]=1ll*inv[i]*i%p; 28 for(int i=1;i<=n;i++) printf("%lld ", 1ll*fac[i-1]*inv[i]%p); 29 }