您的位置:首页 > 其它

FZU 2020-组合(Lucas定理+逆元解决大组合数求模)

2015-08-28 15:56 489 查看
题目地址:FZU 2020

题意:求C(n,m)%p的值(1 <= m <= n <= 10^9, m <= 10^4, m < p < 10^9, p是素数)。

思路:

对于



并且p是素数,我们一般采用Lucas定理来解。

1).Lucas定理是用来求 C(n,m) mod p的值,p是素数。其描述为:

如果



那么得到





Lucas(n,m,p)=C(n%p,m%p)* Lucas(n/p,m/p,p)

Lucas(n,0,p)=1;

2).对于大组合数求模C(N,M)%P=N! / (M! * (N-M)! ) % mod

=( N-M+i )! / M!*(i>=1&&i<=M)。然后根据乘法逆元将除法变成乘法即可。

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef __int64 LL;
const int inf=0x3f3f3f3f;
const double pi= acos(-1.0);
const double esp=1e-6;
using namespace std;
LL n,m,mod;
LL modxp(LL a,LL b)
{
LL res=1;
while(b>0) {
if(b&1)
res=res*a%mod;
b=b>>1;
a=a*a%mod;
}
return res;
}

LL C(LL n, LL m)
{
if(m>n) return 0;
LL ans=1;
for(int i=1; i<=m; i++) {
LL a=(n+i-m)%mod;
LL b=i%mod;
ans=ans*(a*modxp(b, mod-2)%mod)%mod;
}
return ans;
}
LL Lucas(LL n,LL m)
{
if(m==0) return 1;
return C(n%mod,m%mod)*Lucas(n/mod,m/mod)%mod;
}
int main()
{
int T;
scanf("%d",&T);
while(T--) {
scanf("%lld %lld %lld",&n,&m,&mod);
printf("%lld\n",Lucas(n,m));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: