Lucas定理:
C
a
b
C_a^b
Cab?
m
o
d
mod
mod
p
p
p
=
=
=
C
b
/
p
a
/
p
?
C
a
m
o
d
??
p
b
m
o
d
??
p
C_{b/p}^{a/p}*C_{a\\\mod p}^{b\\\mod p}
Cb/pa/p??Camodpbmodp?
m
o
d
mod
mod
p
p
p
Lucas板子:
int qmi(int a, int k, int p)
{
int res = 1 % p;
while (k)
{
if (k & 1) res = (LL)res * a % p;
a = (LL)a * a % p;
k >>= 1;
}
return res;
}
int C(int a, int b, int p)
{
if (a < b) return 0;
LL x = 1, y = 1;
for (int i = a, j = 1; j <= b; i --, j ++ )
{
x = (LL)x * i % p;
y = (LL) y * j % p;
}
return x * (LL)qmi(y, p - 2, p) % p;
}
int lucas(LL a, LL b, int p)
{
if (a < p && b < p) return C(a, b, p);
return (LL)C(a % p, b % p, p) * lucas(a / p, b / p, p) % p;
}
Lucas例题
Saving Beans HDU - 3037
ac代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int qmi(int a, int k, int p)
{
int res = 1 % p;
while (k)
{
if (k & 1) res = (LL)res * a % p;
a = (LL)a * a % p;
k >>= 1;
}
return res;
}
int C(int a, int b, int p)
{
if (a < b) return 0;
LL x = 1, y = 1;
for (int i = a, j = 1; j <= b; i --, j ++ )
{
x = (LL)x * i % p;
y = (LL) y * j % p;
}
return x * (LL)qmi(y, p - 2, p) % p;
}
int lucas(LL a, LL b, int p)
{
if (a < p && b < p) return C(a, b, p);
return (LL)C(a % p, b % p, p) * lucas(a / p, b / p, p) % p;
}
int main()
{
int t; cin >> t;
while(t --)
{
int n, m, p;
cin >> n >> m >> p;
cout << lucas(n+m, m, p) << endl;
}
return 0;
}
|