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

题目地址: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rocky0429

一块也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值