1. 程式人生 > >盧卡斯定理的模板以及應用

盧卡斯定理的模板以及應用

定義:
Lucas定理是用來求 C(n,m) MOD p,p為素數的值。Lucas定理:我們令n=sp+q,m=tp+r.qrp
那麼:(在程式設計時你只要繼續對 呼叫 Lucas 定理即可。程式碼可以遞迴的去完成這個過程,其中遞迴終點為 t=0 ;時間複雜度 Ologp(n)p)
主要解決當 n,m 比較大的時候,而 p 比較小的時候 <1e6 ,那麼我們就可以藉助 盧卡斯定理來解決這個問題:
模板:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath> #include <vector> #include <queue> #include <algorithm> #include <set> using namespace std; typedef long long LL; typedef unsigned long long ULL; const int INF = 1e9+5; const int MAXN = 1e6+5; const int MOD = 1e9+7; const double eps = 1e-7; const double
PI = acos(-1); using namespace std; LL quick_mod(LL a, LL b, LL c) { LL ans = 1; while(b) { if(b & 1) ans = (ans*a)%c; b>>=1; a = (a*a)%c; } return ans; } LL fac[MAXN]; void Get_Fac(LL m)///m! { fac[0] = 1; for(int i=1; i<=m; i++) fac[i] = (fac[i-1
]*i) % m; } LL Lucas(LL n, LL m, LL p) { LL ans = 1; while(n && m) { LL a = n % p; LL b = m % p; if(a < b) return 0; ans = ( (ans*fac[a]%p) * (quick_mod(fac[b]*fac[a-b]%p,p-2,p)) ) % p; n /= p; m /= p; } return ans; } int main() { LL n, m, p; Get_Fac(p); Lucas(n, m, p);///C(n,m)%p return 0; }

應用:
HDU 3037
題目大意:
C(n+m,m) % P
AC

/**
2016 - 08 - 04 晚上
Author: ITAK

Motto:

今日的我要超越昨日的我,明日的我要勝過今日的我,
以創作出更好的程式碼為目標,不斷地超越自己。
**/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int INF = 1e9+5;
const int MAXN = 1e6+5;
const int MOD = 1e9+7;
const double eps = 1e-7;
const double PI = acos(-1);
using namespace std;
LL quick_mod(LL a, LL b, LL c)
{
    LL ans = 1;
    while(b)
    {
        if(b & 1)
            ans = (ans*a)%c;
        b>>=1;
        a = (a*a)%c;
    }
    return ans;
}
LL fac[MAXN];
void Get_Fact(LL m)///m!
{
    fac[0] = 1;
    for(int i=1; i<=m; i++)
        fac[i] = (fac[i-1]*i) % m;
}
LL Lucas(LL n, LL m, LL p)
{
    LL ans = 1;
    while(n && m)
    {
        LL a = n % p;
        LL b = m % p;
        if(a < b)
            return 0;
        ans = ( (ans*fac[a]%p) * (quick_mod(fac[b]*fac[a-b]%p,p-2,p)) ) % p;
        n /= p;
        m /= p;
    }
    return ans;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        LL n, m, p;
        scanf("%I64d%I64d%I64d",&n,&m,&p);
        Get_Fact(p);
        printf("%I64d\n",Lucas(n+m,m,p));
    }
    return 0;
}