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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章