Lucas定理模板

时间:2022-04-14 03:48:13

用于大组合数对p取模的计算。

 #include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 100010
typedef long long LL; LL m,n,p;
LL Pow(LL a,LL b,LL mod)
{
LL ans=;
while(b)
{
if(b&)
{
b--;
ans=(ans*a)%mod;
}
b>>=;
a=(a*a)%mod;
}
return ans;
}
LL C(LL n,LL m)
{
if(n<m) return ;
if(m == ) return ;
if(m < ) return ;
LL ans=;
for(int i=;i<=m;i++)
{
ans=ans*(((n-m+i)%p)*Pow(i,p-,p)%p)%p; //除以一个数的话是乘以其逆元,用到费马小定理
}
return ans;
}
LL Lucas(LL n,LL m)
{
if(m==)
return ;
return (Lucas(n/p,m/p)*C(n%p,m%p))%p;
}
int main()
{
while(cin>>n>>m){
p=;
LL l=n+m-,r=n-;
printf("%I64d\n",Lucas(l,r)); //计算C(l, r)
}
return ;
}