Formulation
For non-negative integers m and n and a prime p, the following congruence relation holds:
where
and
are the base p expansions of m and n respectively.
Lucas 定理:将m写出p进制a[k], a[k-1], a[k-2] ... a[0],n写出p进制b[k], b[k-1], b[k-2], ... b[0]。
那么C(n, m) = C(a[0], b[0])*C(a[1], b[1])*...*C(a[k], B[k]) (mod p)
代码递归实现Lucas(n, m) % p
int Lucas(LL n, LL m, LL p)
{
if(m == 0)
return 1 % p;
else
return C(n%p, m%p, p) * Lucas(n/p, m/p, p);
}
这里可以利用费马小定理a^(p-1) = 1 (mod p) -> a^(p-2) = a^(-1) (mod p)。
C(n, m, p) = n! * (m! (n-m)!)^(p-2)。
在计算时我们一般都是先预处理阶乘。
Lucas代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 1000
#define LL long long
using namespace std;
int fac[MAXN];//存储阶乘
void getfac(LL p)//预处理阶乘 前p个数就可以了
{
fac[0] = 1 % p;
for(LL i = 1; i <= p; i++)
fac[i] = fac[i-1] * i % p;
}
LL pow_mod(LL a, LL n, LL p)//求解逆元
{
LL ans = 1 % p;
while(n)
{
if(n & 1)
ans = ans * a % p;
a = a * a % p;
n >>= 1;
}
return ans;
}
LL C(LL n, LL m, LL p)
{
if(m > n) return 0;
else return fac[n] * pow_mod(fac[m] * fac[n-m] % p, p-2, p);
}
LL Lucas(LL n, LL m, LL p)
{
if(m == 0)
return 1 % p;
else
return C(n%p, m%p, p) * Lucas(n/p, m/p, p) % p;
}
int main()
{
LL n, m, p;//求解C(n, m) % p
while(scanf("%lld%lld%lld", &n, &m, &p) != EOF)
{
getfac(p);
printf("%lld\n", Lucas(n, m, p));
}
return 0;
}