卢卡斯定理模板

卢卡斯定理模板
适用于求 C(n,m) % p 在 p 比较大又不是特别大的情况。

#include 
using namespace std;
using ll = long long;
const int maxn=1e5+5;
ll n,m,p;
ll quick_mod(ll a, ll b, ll m) {
    ll ans = 1;
    while (b) {
        if (b & 1) {
            ans = ans * a % m;
        }
        a = a * a % m;
        b >>= 1;
    }
    return ans;
}
 
ll comp(ll a, ll b, ll m) {
    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 (int i = 0; i < b; i++) {
        ca = ca * (a - i) % m;
        cb = cb * (b - i) % m;
    }
    ans = ca * quick_mod(cb, m - 2, m) % m;
    return ans;
}
 
ll lucas(ll a, ll b, ll m) {
    ll ans = 1;
    while (a && b) {
        ans = (ans * comp(a % m, b % m, m)) % m;
        a /= m;
        b /= m;
    }
    return ans;
}
 
int main() {
	std::ios::sync_with_stdio(false);
	int T;
	cin >> T;
	long long n, p, m;
	while (T--) {
		cin >> n >> m >> p;
		cout << lucas(n+m, n, p) << endl;	
	}
	return 0;
}

你可能感兴趣的:(杂谈)