Lucas定理是用来求 c(n,m) mod p,p为素数的值。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define maxn 100005
#define ll long long
using namespace std;
int n,m,p,t;
ll qpow(ll x,int k){
ll ret=1;
while(k){
if(k&1) ret=(ret*x)%p;
x=(x*x)%p;
k>>=1;
}
return ret;
}
ll C(int x,int y){
ll ret=1;
if(x<y) return 0;//这玩意坑害了我好久···一定要加QAQ
for(int i=y+1;i<=x;i++) ret=(ret*1ll*i)%p;
for(int i=2;i<=x-y;i++) ret=(ret*qpow(i,p-2))%p;
// for(int i=2;i<=y;i++) ret=(ret*qpow(i,p-2))%p;
return ret;
}
ll Lucas(int n,int m){
if(n<p && m<p) return C(n,m)%p;
return (C(n%p,m%p)*Lucas(n/p,m/p))%p;
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d%d%d",&n,&m,&p);
n=n+m;
printf("%lld\n",Lucas(n,m));
}
return 0;
}