正题
题目链接:https://www.luogu.org/problem/P3807
题目大意
求Cn+mm%pC_{n+m}^m\% pCn+mm%p
LucasLucasLucas定理
Cnm%p=C⌊np⌋⌊mp⌋∗Cn%pm%pC_{n}^m\% p=C_{\lfloor \frac{n}{p}\rfloor}^{\lfloor \frac{m}{p}\rfloor}*C_{n\%p}^{m\%p}Cnm%p=C⌊pn⌋⌊pm⌋∗Cn%pm%p
解题思路
预处理好1∼p1\sim p1∼p的阶乘,根据LucasLucasLucas定理递推计算下去。
codecodecode
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
ll T,n,m,p,a[110000];
ll power(ll x,ll b,ll p)
{ll ans=1;while(b){if(b&1) ans=ans*x%p;x=x*x%p;b>>=1;}return ans;
}
ll C(ll n,ll m,ll p)
{if(m>n) return 0ll;return a[n]*power(a[m],p-2,p)%p*power(a[n-m],p-2,p)%p;
}
ll lucas(ll n,ll m,ll p)
{if(!m) return 1ll;return lucas(n/p,m/p,p)*C(n%p,m%p,p)%p;
}
int main()
{scanf("%lld",&T);while(T--){scanf("%lld%lld%lld",&n,&m,&p);a[0]=1;for(ll i=1;i<=p;i++)a[i]=a[i-1]*i%p;printf("%lld\n",lucas(n+m,m,p));}return 0;
}