Lucas定理在ACM中的应用

首先,Lucas(卢卡斯)定理是什么?有什么用?

Lucas定理是用来求 C(n,m) mod p,p为素数的值(注意:p一定是素数)

有人会想,C(n,m)不能用C(n, m) = C(n - 1,m) + C(n - 1, m - 1)的公式来递推吗?

( 提示:C(n, m) mod p = n!/(m!(n - m)!) mod p )



可以是可以。但当n,m,p都很大时,你递推所用的时间就会很爆炸了。所以,这就需要用到Lucas定理来解决了。

因此,Lucas定理用来解决大组合数求模是很有用的



注意:Lucas定理最大的数据处理能力是p在10^5左右,不能再大了。再大的话,我就不知道了。。。智障啊

表达式:C(n,m)%p=C(n/p,m/p)*C(n%p,m%p)%p。(可以递归)

递归方程:(C(n%p, m%p)*Lucas(n/p, m/p))%p。(递归出口为m==0,return 1)


-----------------------------------------------------------------------

Lucas定理定义

这里我们令n=sp+q , m=tp+r .(q ,r ≤p)

 那么: 


在编程时你只要继续对
 
调用Lucas定理即可。
代码可以递归的去完成这个过程,其中递归终点为 t = 0  )
(时间复杂度 O(logp(n)*p) :)

-------------------------------------------------------------------------------------------

Lucas定理 证明
首先你需要这个算式其中f > 0&& f < p。
然后(1 + x) nΞ(1 + x) sp+q Ξ( (1 + x)p)s· (1 + x) q Ξ(1 + xps· (1 + x) q(mod p) 

所以得(1 + x) sp+q  
我们求右边的
 
的系数为:
求左边的
 
为:
通过观察你会发现当且仅当i = t , j = r ,能够得到 的系数,及
所以,得证。
--------------------------------------------------------------------------------------------------
我再次将它公式化一下。
For non-negative integers m and n and a prime p, the following congruence relation holds:

where

and

are the base  p  expansions of  m  and  n  respectively.
已知C(n, m) mod p = n!/(m!(n - m)!) mod p。显然是除法取模,这里又要用到m!(n-m)!的逆元。
求逆元(此处不详细说明了(ˇˍˇ) )。。。
根据费马小定理

已知(a, p) = 1,则 ap-1 ≡ 1 (mod p),  所以 a*ap-2 ≡ 1 (mod p)。

也就是 (m!(n-m)!)的逆元为 (m!(n-m)!)p-2 。


按照上面的思路就可以写出Lucas定理的代码了:
#include <iostream>
using namespace std;
typedef long long ll;
ll N,M,fac[10010];
ll p=10007;

ll fast_pow(ll a,ll k,ll mod){
    ll ans=1;
    while(k){
        if(k&1) ans=(ans*a)%mod;
        a=(a*a)%mod;
        k>>=1;
    }
    return ans;
}

ll C(ll n,ll r){
    if(n<r)
        return 0;
    return fac[n]*fast_pow(fac[r]*fac[n-r],p-2,p)%p;
}

ll lucas(ll n,ll m){
    if(m==0)
        return 1;
    return (C(n%p,m%p)*lucas(n/p,m/p))%p;
}

int main(){
    fac[0]=1;
    for(int i=1;i<p;i++)
        fac[i]=fac[i-1]*i%p;
    while(cin>>N>>M)
        cout<<lucas(N,M)<<endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/a493823882/article/details/79612950