大组合数Lucas

https://blog.csdn.net/sr_19930829/article/details/39058487

 LL Lucas(LL n, LL m, int p){
        return m ? Lucas(n/p, m/p, p) * comb(n%p, m%p, p) % p : 1;
 }

Saving Beans HDU3037

 

#include <iostream>
#include <string.h>
#include <cmath>
using namespace std;
typedef long long ll;
const int maxm = 1e5 + 5;
ll fac[maxm];

void init(ll p) {
    fac[0]=1;
    for(int i = 1; i <= p; i++)
        fac[i] = fac[i - 1] * i % p;
}

ll qpow(ll x, ll n, ll mod) {
    ll res = 1;
    while (n > 0) {
        if (n & 1) {
            res = res * x % mod;
        }
        x = x * x % mod;
        n >>= 1;
    }
    return res;
}

ll lucas(ll n, ll m, ll p)
{
    ll res = 1;
    while(n && m)
    {
        ll a = n % p;
        ll b = m % p;
        if(a < b) return 0;
        res = (res * fac[a] * qpow(fac[b] * fac[a - b] % p, p - 2, p)) % p;
        n /= p;
        m /= p;
    }
    return res;
}

int t;
ll n, m, p;
int main() {
    scanf("%d", &t);
    while(t--) {
        scanf("%lld%lld%lld", &n, &m, &p);
        init(p);
        printf("%lld\n", lucas(n + m, m, p));
    }
    return 0;
}

 

posted @ 2019-02-19 12:06  downrainsun  阅读(151)  评论(0)    收藏  举报