四种求组合数方法
1.组合数公式
2.递推
// c[a][b] 表示从a中选b个的方案数
for (int i = 0; i < N; i ++ )
for (int j = 0; j <= i; j ++ )
if (!j) c[i][j] = 1;
else c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod;
3.预处理阶乘和逆元 常用
// a 的 k 次方 mod p (p为质数)
int qmi(int a, int k, int p) //快速幂模板
{
int res = 1;
while (k)
{
if (k & 1) res = (long long)res * a % p;
a = (long long)a * a % p;
k >>= 1;
}
return res % p;
}
// a 为求逆元的数,b 为模数,运算完成后 x 就是在模数为 b 下 a 的逆元
int exgcd(int a, int b, int &x, int &y)
{
if (!b)
{
x = 1, y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
4.卢卡斯定理 常用
#include<iostream>
using namespace std;
typedef long long LL;
int p;
int ksm(int a, int b) // 快速幂
{
int res = 1;
while (b)
{
if (b & 1)res = (LL)res * a % p;
a = (LL)a * a % p;
b >>= 1;
}
return res;
}
int C(int a, int b) // 组合数 C
{
int res = 1;
for (int i = 1, j = a; i <= b; i++, j--)
{
res = (LL)res * j % p;
res = (LL)res * ksm(i, p - 2) % p;
}
return res;
}
int lucas(LL a, LL b) // 卢卡斯
{
if (a < p && b < p) return C(a, b);
return (LL)C(a % p, b % p) * lucas(a / p, b / p) % p;
}
int main()
{
int n;
cin >> n;
while (n--)
{
LL a, b;
cin >> a >> b >> p;
int res = lucas(a, b);
cout << res << endl;
}
return 0;
}