hau 3037 Saving Beans【Lucas定理】

题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=3037

代码:

#include <iostream>
#include <cmath>
#include <cstdio>

using namespace std;

long long pow(long long a, long long b, long long c)
{
    long long tmp = 1;
    while (b)
    {
        if (b & 1) tmp = (tmp*a) % c;
        a = (a*a) % c;
        b >>= 1;
    }
    return tmp;
}

long long fac[100005];

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

long long Lucas(long long n, long long m, long long p)
{
    long long tmp = 1;
    while (n && m)
    {
        long long a = n%p,b = m%p;
        if (a < b) return 0;
        tmp = (tmp * fac[a] * pow(fac[b] * fac[a - b] % p, p - 2, p)) % p;

        n /= p;
        m /= p;
    }
    return tmp;
}

int main()
{
    long long n, m, p;
    int T;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%lld%lld%lld", &n, &m, &p);
        get_fac(p);
        printf("%lld\n", Lucas(n + m, m, p));
    }
    return 0;
}

你可能感兴趣的:(hau 3037 Saving Beans【Lucas定理】)