lucas模板

代码:

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
#define per(i,a,b) for(int i=a;i<=b;i++)
#define ber(i,a,b) for(int i=a;i>=b;i--)
const int N = 1e5+1000;
const double eps = 1e-2;
LL f[N], g[N],n,m,p;//f(i)存i!,g存i!的逆元
LL  quick(LL a, LL b, LL mod)
{
    LL ans = 1;
    while (b)
    {
        if (b & 1)
            ans = ans * a % mod;
        b >>= 1;
        a = a * a % mod;
    }
    return ans;
}
LL quic(LL n, LL m, LL p)
{
    if (m > n) return 0;
    return f[n] * g[n-m]%p* g[m] % p;
}
LL lucas(LL n, LL m, LL p)
{
    if (m == 0)
        return 1;
    return lucas(n / p, m / p, p) * quic(n % p, m % p, p)%p;
}
int main()

    int T;
    cin >> T;
    while (T--)
    {
        cin >> n >> m >> p;
        f[0] = 1;
        g[0] = 1;
        for (int i = 1; i <=p; i++)
        {
            f[i] = f[i - 1] * i % p;
            g[i] = g[i - 1] * quick(i, p - 2, p)%p;
        }
        LL ans = lucas(n+m, n, p);
        cout << (ans%p+p)%p << endl;
    }  
    return 0;
}

你可能感兴趣的:(数论,算法,c++,图论)