目的:输入m, n, p,求出C(m,n)%p的精确值
基础:
1、费马小定理:已知整数a和质数p,其中Gcd(a, p)==1,那么a^(p-1)%p==1恒成立
2、要求出(a/b)%p的值(p一定为质数),可将其转化为a*b^(-1)%p,其中b^(-1)为b的逆元,而因为
b^(p-1)%p==1,所以b与b^(p-2)互为逆元,所以(a/b)%p==a*b^(p-2)%p
Lucas步骤:
1、C(m,n)%p = C(m/p, n/p)%p * C(m%p, n%p)%p(递归)
2、C(m,n)%p = (m!/(m-n)! / n!)%p = (m!/(m-n)! * (n!)^(p-2))%p(对于上面的C(m%p, n%p)%p进行计算)
3、用快速幂计算x^(p-2)
版本1:直接计算C(m,n)
#include<stdio.h>
#define LL long long
LL Pow(LL a, LL b, LL mod);
LL C(LL m, LL n, LL p);
LL Lucas(LL m, LL n, LL p);
int main(void)
{
LL m, n, p;
while(scanf("%lld%lld%lld", &m, &n, &p)!=EOF) /*输入保证p为质数*/
printf("%lld\n", Lucas(m, n, p));
return 0;
}
LL Pow(LL a, LL b, LL mod)
{
LL sum;
sum = 1;
while(b)
{
if(b%2==1)
sum = (sum*a)%mod;
a = (a*a)%mod;
b /= 2;
}
return sum;
}
LL C(LL m, LL n, LL p)
{
LL i, ans;
ans = 1;
if(m<n)
return 0;
for(i=1;i<=n;i++)
ans = ans*(((m-n+i)%p)*Pow(i, p-2, p)%p)%p;
return ans;
}
LL Lucas(LL m, LL n, LL p)
{
if(m==0)
return 1;
return (Lucas(m/p, n/p, p)*C(m%p, n%p, p))%p;
}
版本2:
lightoj 1067 - Combinations(求C(n,m),n和m都小于1000000,但有百万组测试实例)
这个时候需要对阶乘打表,并直接用组合数公式
#include<stdio.h>
#define LL long long
LL Pow(LL a, LL b, LL mod);
LL C(LL m, LL n, LL p);
LL Lucas(LL m, LL n, LL p);
long long jc[1000005] = {1};
int main(void)
{
int T, cas, i;
LL m, n, p;
p = 1000003;
for(i=1;i<=1000000;i++)
jc[i] = (jc[i-1]*i)%p;
scanf("%d", &T);
cas = 1;
while(T--)
{
scanf("%lld%lld", &n, &m);
printf("Case %d: %lld\n", cas++, Lucas(n, m, p));
}
return 0;
}
LL Pow(LL a, LL b, LL mod)
{
LL ans;
ans = 1;
while(b)
{
if(b%2==1)
ans = (ans*a)%mod;
a = (a*a)%mod;
b /= 2;
}
return ans;
}
LL C(LL n, LL m, LL p)
{
LL ans;
if(n<m)
return 0;
ans = (jc[n]*Pow((jc[m]*jc[n-m])%p, p-2, p)%p)%p;
return ans;
}
LL Lucas(LL n, LL m, LL p)
{
if(m==0)
return 1;
return (Lucas(n/p, m/p, p)*C(n%p, m%p, p))%p;
}
其实到这里,你会发现很多时候Lucas并用不到,主要是求组合数
而是上面的程序只是将阶乘打了表,逆元还是暴力计算幂次方
所以有了版本3(速度最快,O(1)查询):阶乘打表+线性求逆元(完全预处理)
#include<stdio.h>
#define LL long long
#define mod 1000000007
LL Pow(LL a, LL b);
LL C(LL m, LL n);
LL Lucas(LL m, LL n);
LL Fan(LL n, LL m);
LL inv[2000005] = {1}, jc[2000005] = {1};
int main(void)
{
LL T, m, n, k, i;
for(i=1;i<=2000001;i++)
jc[i] = (jc[i-1]*i)%mod;
inv[2000001] = Pow(jc[2000001], mod-2);
for(i=2000000;i>=1;i--)
inv[i] = inv[i+1]*(i+1)%mod;
scanf("%lld", &T);
while(T--)
{
scanf("%lld%lld%lld", &n, &m, &k);
printf("%lld\n", Fan(m-1, m-k)*Fan(n-(m-k), n-m)%mod);
}
return 0;
}
LL Fan(LL n, LL m)
{
LL all;
all = n+m;
return (C(all, n)-C(all, n+1)+mod)%mod;
}
LL Pow(LL a, LL b)
{
LL ans;
ans = 1;
while(b)
{
if(b%2==1)
ans = (ans*a)%mod;
a = (a*a)%mod;
b /= 2;
}
return ans;
}
LL C(LL n, LL m)
{
LL ans;
if(n<m)
return 0;
ans = jc[n]*inv[m]%mod*inv[n-m]%mod;
return ans;
}