lucas定理

题目链接
大佬博客还有扩展lucas
题意:给你n和m求C(n,m)。
C(n,m)=n!/(m!*(n-m)!);
当题目数据不是很大的时候可以打表,存一个阶乘表和逆元表,这样就可以直接计算了,但是当n和m很大的时候,就要用lucas定理了,前提是模数要是素数。
lucas定理:C(n,m)%p=C(n/p,m/p)*C(n%p,m%p)%p;
逆元:由费马小定理a ^ (p-1) = 1 (%p),两边同时除去a则a ^ (p-2) = a^-1 (%p),得a的逆元a^-1 = a ^ (p-2)。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn=1e6+10;
const LL mod=1000003;
LL fac[maxn];
void init()
{
    fac[0]=1;
    for(int i=1;i<maxn;i++)//阶乘表
        fac[i]=(i*fac[i-1])%mod;
}
LL quickpow(LL a,LL k)//求逆元
{
    LL res=1;
    while(k)
    {
        if(k&1)
            res=(res*a)%mod;
        a=(a*a)%mod;
        k>>=1;
    }
    return res;
}
LL C_n_m(LL n,LL m)//求C(n,m);
{
    LL ans=1;
    ans=fac[n]*quickpow(fac[m]*fac[n-m]%mod,mod-2)%mod;
    return ans;
}
LL lucas(LL n,LL m)
{
    LL ans=1;
    if(n<m) return 0;
    while(n&&m&&ans)
    {
        ans=ans*C_n_m(n%mod,m%mod)%mod;
        n/=mod;
        m/=mod;
    }
    return ans;
}
int main()
{
    init();
    int ncase,Z=0;
    scanf("%d",&ncase);
    while(ncase--)
    {
        LL n,m;
        scanf("%lld%lld",&n,&m);
        printf("Case %d: %lld\n",++Z,lucas(n,m));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值