求组合,卢卡斯方法

LL exp_mod(LL a, LL b, LL mod) {
    LL res = 1;
    while(b != 0) {
        if(b&1) res = (res * a) % mod;
        a = (a*a) % mod;
        b >>= 1;
    }
    return res;
}

LL Comb(LL a, LL b, LL mod) {
    if(a < b)   return 0;
    if(a == b)  return 1;
    if(b > a - b)   b = a - b;

    LL ans = 1, ca = 1, cb = 1;
    for(LL i = 0; i < b; ++i) {
        ca = (ca * (a - i))%mod;
        cb = (cb * (b - i))%mod;
    }
    ans = (ca*exp_mod(cb, mod - 2, mod)) % mod;
    return ans;
}

LL Lucas(int n, int m, int mod) {
     LL ans = 1;

     while(n&&m&&ans) {
        ans = (ans*Comb(n%mod, m%mod, mod)) % mod;
        n /= mod;
        m /= mod;
     }
     return ans;
}
原文地址:https://www.cnblogs.com/wsruning/p/5739956.html