卢卡斯定理在处理组合数学的大数问题是十分有用的,直接上定理,证明也很好证但在这里不在赘述, 直接上定理
下面是洛谷的一道模板题(3807)
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<cstring>
#include<iostream>
using namespace std;
typedef long long ll;
const int N=1e5+5;
ll fact[N];
void init(ll p){
fact[0]=1;
for(int i=1;i<=p;i++)fact[i]=(fact[i-1]*i)%p;
}
ll exgcd(ll a,ll b,ll &x,ll &y){
if(b==0){
x=1;
y=0;
return a;
}
ll d=exgcd(b,a%b,y,x);
y-=(a/b)*x;
return d;
}
ll inv(ll a,ll p){
ll x,y;
if(exgcd(a,p,x,y)!=1)return -1;
return (x%p+p)%p;
}
ll C(ll n,ll m,ll p){
return n>m ? 0: fact[m]*inv(fact[n],p)%p *inv(fact[m-n],p)%p;
}
ll lucas(ll n,ll m,ll p){
return n==0 ? 1%p: lucas(n/p,m/p,p)*C(n%p,m%p,p)%p;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
ll n,m,p;
scanf("%lld%lld%lld",&n,&m,&p);
init(p);
printf("%lld\n",lucas(n,n+m,p));
}
return 0;
}
通过不断的递推可以很快得到组合数通过预处理时间效率可达O(p+logp m)