1.gcd
表示 和 的最大公约数。
而且 又等价于 。证明如下:
设 ,则 ,。其中 是正整数。
又则 。
可以证明,辗转相除后的数的因子总是有最大公约数。
long long Gcd(int x,int y){
if(!y)return x;
else return Gcd(y,x%y);
}2.快速幂
题目算式:。
考虑 的二进制上有 的位表示 ,其中 是正整数。
那么 ,其中 表示 二进制上第 位有没有 。p[i]=b&(1<<i);。
long long Pow(ll x,ll y,ll z){
ll res=1;
while(y){
if(y&1)res=res*a%p;
a=a*a%p;
y>>=1;
}
return res%p;
}3.逆元
,其中 是质数, 是任意数(不包括 )。
定义任意有理数 ,任意质数 。
则有以下同余方程。
看这道模板题:
既然 ,那么根据费马小定理,。
首先考虑朴素做法,快速幂求每个 ,时间复杂度 。 ms显然TLE。
考虑优化,预处理出 到 每个数的阶乘。
再次考虑到,,所以定义 的逆元。
而求每个 的逆元,考虑倒序,每个invf[i]=invf[i+1]*(i+1)%p;。即 。
最后,对于每个 ,可以知道 ,并且可以知道 ,所以,每个 的逆元就可以用 的时间复杂度统计出来。
#include<bits/stdc++.h>
#define IMax 0x3f3f3f3f
#define IMin -0x3f3f3f3f
#define ULL unsigned long long
#define BASE 131
#define pii pair<int,int>
#define fir first
#define sec second
#define ll long long
#define LMax LLONG_MAX
#define LMin LLONG_MIN
#define byzyx cin.tie(0)->ios::sync_with_stdio(0);
using namespace std;
inline void read(int &x){
int f=1;x=0;char s=getchar();
while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
x*=f;
}
const int N=3e6+5;
ll n,p,fac[N],invf[N];
ll Pow(ll a,ll b,ll c){
ll res=1;
while(b){
if(b&1)res=res*a%c;
a=a*a%p;
b>>=1;
}
return res;
}
signed main(void){
byzyx
cin>>n>>p;
fac[0]=1;
for(int i=1;i<=n;i++)fac[i]=fac[i-1]*i%p;
invf[n]=Pow(fac[n],p-2,p);
for(int i=n-1;i>=1;i--)invf[i]=invf[i+1]*(i+1)%p;
for(int i=1;i<=n;i++){
cout<<invf[i]*fac[i-1]%p<<'\n';
}
return 0;
}