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));
    }
}
发布了110 篇原创文章 · 获赞 18 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章