![[Luogu 3807]【模板】卢卡斯定理 [Luogu 3807]【模板】卢卡斯定理](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
Description
给定n,m,p(1≤n,m,p≤10^5)
求 C_{n+m}^{m} \mod p
保证P为prime
C表示组合数。
一个测试点内包含多组数据。
Input
第一行一个整数T(T≤10),表示数据组数
第二行开始共T行,每行三个数n m p,意义如上
Output
共T行,每行一个整数表示答案。
Sample Input
2
1 2 5
2 1 5
Sample Output
3
3
题解
$Lucas$定理。
就是$C^m _n \mod p = C^{m/p} _{n/p}*C^{m \mod p} _{n \mod p} \mod p$。
证明:不会。记着就行。
代码实现方面,注意两点:
1.对于$C^{m/p} _{n/p}$部分可以继续使用$Lucas$定理递归求解。
2.求逆元,可以用费马小定理做快速幂,当然也可以线性预处理阶乘逆元。注意,若线性预处理,需要将$0$位赋为$1$(很好理解,不做解释)。
//It is made by Awson on 2017.10.7
#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
using namespace std;
const int N = 1e5; int n, m, p;
int A[N+], B[N+]; int C(int n, int m, int p) {
if (m > n) return ;
return (LL)A[n]*B[n-m]%p*B[m]%p;
}
int Lucas(int n, int m, int p) {
if (!m) return ;
return (LL)C(n%p, m%p, p)*Lucas(n/p, m/p, p)%p;
}
void work() {
scanf("%d%d%d", &n, &m, &p);
A[] = B[] = A[] = B[] = ;
n += m;
for (int i = ; i <= p; i++)
B[i] = -(LL)(p/i)*B[p%i]%p;
for (int i = ; i <= p; i++)
A[i] = (LL)A[i-]*i%p,
B[i] = (LL)B[i-]*B[i]%p;
printf("%d\n", (Lucas(n, m, p)+p)%p);
}
int main() {
int t;
scanf("%d", &t);
while (t--)
work();
return ;
}