卢卡斯定理

当 p 为质数时

\[c_m^n \equiv c_{m\%p}^{n\%p} * c_{m/p}^{n/p}\pmod p \]

模版,注意这其中的逆元求法

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define ll long long
using namespace std;
const int MAXN = 200005;
int T, n, m, p;
ll fac[MAXN], ni[MAXN];
ll lucas(int a, int b, int p) {
	if(a < b) return 0;
	if(a < p) return fac[a] * ni[b] * ni[a - b] % p;
	else return lucas(a / p, b / p, p) * lucas(a % p, b % p, p) % p;
}
int main() {
	cin >> T;
	while(T--) {
		cin >> n >> m >> p;
		fac[0] = fac[1] = ni[0] = ni[1] = 1;
		for(int i = 2; i <= n + m; i++) {
			(fac[i] = fac[i - 1] * i) %= p;
		}
		for(int i = 2; i <= n + m; i++) {
			(ni[i] = (p - p/i) * ni[p % i]) %= p;
		}
		for(int i = 2; i <= n + m; i++) {
			(ni[i] *= ni[i - 1] ) %= p;
		}
		cout << lucas(n + m, m, p) << endl;
	}
	return 0;
}
posted @ 2018-03-23 20:25  Mr_Wolfram  阅读(141)  评论(0编辑  收藏  举报