【模板】卢卡斯定理 / Lucas 定理
题目跳转
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
ll x=0,f=1,ch=gc();
while(ch!=EOF&&(ch<'0'||ch>'9')){
if(ch=='-'){
f=-1;
}
ch=gc();
}
if(ch==EOF){
return x;
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch-'0');
ch=gc();
}
return x*f;
}
uint8_t obuf[1<<20],*op=obuf;
#define fls() (fwrite(obuf,1,op-obuf,stdout),op=obuf,0)
#define pc(ch) (op==obuf+(1<<20)?fls():0,*op++=(ch))
void write(ll x){
if(x<0){
x=-x;
pc('-');
}
if(x>9){
write(x/10);
}
pc(x%10+'0');
}
const ll maxn=1e5+5;
ll t,n,m,p,po[maxn];
ll ksm(ll a,ll b){
ll res=1;
while(b){
if(b&1){
res=res*a%p;
}
a=a*a%p;
b>>=1;
}
return res;
}
ll c(ll a,ll b){
if(a<b){
return 0;
}
return po[a]*ksm(po[b]*po[a-b]%p,p-2);
}
ll lucas(ll a,ll b){
return a==0?1:c(a%p,b%p)*lucas(a/p,b/p)%p;
}
void solve(){
n=rd();
m=rd();
p=rd();
po[0]=1;
for(ll i=1;i<=p;i++){
po[i]=po[i-1]*i%p;
}
write(lucas(n+m,n));
pc('\n');
}
int main(){
t=rd();
for(ll i=1;i<=t;i++){
solve();
}
fls();
return 0;
}
Goodbye!

浙公网安备 33010602011771号