hdu 3037 费马小定理+逆元求组合数+Lucas定理

组合数学推推推最后,推得要求C(n+m,m)%p

其中n,m小于10^9,p小于1^5

用Lucas定理求(Lucas定理求nm较大时的组合数)

因为p数据较小可以直接阶乘打表求逆元

求逆元时,由费马小定理知道p为素数时,a^p-1=1modp可以写成a*a^p-2=1modp

所以a的逆元就是a^p-2,

可以求组合数C(n,m)%p中除法取模,将其转化为乘法取模
即    /(m!*(n-m)!)=*(m!*(n-m)!)^p-2


#include <iostream>
#define ll long long
const int N=1e5+5;

using namespace std;
ll fac[N],p;
void init()
{
    fac[0]=1;
    for(int i=1;i<=p;i++)
        fac[i]=fac[i-1]*i%p;
}
ll qpow(ll a,ll b)
{
    ll ans=1;
    a%=p;
    while(b)
    {
        if(b&1)
        {
            ans=ans*a%p;
        }
        b>>=1;
        a=a*a%p;
    }
    return ans;
}
ll C(ll a,ll b)
{
    if(a<b) return 0;
    return fac[a]*qpow(fac[b]*fac[a-b],p-2)%p;
}
ll Lucas(ll a,ll b)
{
    if(b==0) return 1;
    return (C(a%p,b%p)*Lucas(a/p,b/p))%p;
}
int main()
{
    int T;
    ll n,m;
    cin>>T;
    while(T--)
    {
        cin>>n>>m>>p;
        init();
        cout<<Lucas(n+m,m)<<endl;
    }
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值