逆元求组合数中作用就是讲公式中的除法取余转化为乘法取余,其实当m≤10^5时,都可以直接暴力求分子中每个因子的逆元(会用到快速幂),这里需要先求出p的欧拉函数值。 此处n,p的值在数据范围(10^18)内就行
除了上面的思路,我们也可以O(n)打表得出1!~n!的逆元对p取模后的结果:求逆元的方法总结、打表,这时就不需要用到快速幂求逆元,但此时对n的范围就有要求了:n≤10^6, m≤10^6
打表代码实现:
注意:需要满足条件n<p
inv[1]=1;
for(int i=2;i<=n;++i)
inv[i]=p-p/i*inv[p%i]%p;
for(int i=2;i<=n;++i)
inv[i]=(inv[i]*inv[i-1])%p;
例题:P3807 【模板】卢卡斯定理
代码:
#include <iostream>
#include<stdio.h>
#include<cmath>
#include<algorithm>
#define mod 1000000007
#include<string.h>
using namespace std;
typedef long long LL;
const int manx=2e5+7;
LL a[manx],b[manx];
LL Lucas(LL n,LL m,LL p)
{
if(n<m) return 0;
else if(n<p) return (b[n]*a[m]%p)*a[n-m]%p;
else return Lucas(n/p,m/p,p)*Lucas(n%p,m%p,p)%p;
}
int main()
{
LL n,m,p,t;
scanf("%lld",&t);
while(t--)
{
scanf("%lld%lld%lld",&n,&m,&p);
a[0]=a[1]=b[0]=b[1]=1;
for(int i=2;i<=n+m;i++) b[i]=b[i-1]*i%p;
for(int i=2;i<=n+m;i++) a[i]=(p-p/i)*a[p%i]%p;
for(int i=2;i<=n+m;i++) a[i]=a[i-1]*a[i]%p;
printf("%lld\n",Lucas(n+m,m,p));
}
}
因为这里n+m可能会大于p,所以需要用卢卡斯转化一下。