题意:输出C(n,m)%p的值,其中(1 <= m <= n <= 10^9, m <= 10^4, m < p < 10^9, p是素数)。
解题思路:C(n,m) = [n*(n-1)*(n-2)*...*(n-m+1)]/[1*2*3*...*m].
令 a = [n*(n-1)*(n-2)*...*(n-m+1)];
b = [1*2*3*...*m];
x = C(n,m)%p;
如果(a,p)=1,(b,p) = 1,
则:(a/b)≡x(mod p);
==>a≡b*x(mod p);
令 a` = a%p; b` = b%p;
则:a`≡b`*x(mod p)
==>b`*x+k*p = a` (p为素数,gcd(b`,p)=1,方程一定有解)
应用拓展欧几里得解得x的最小正整数解即为结果。
注意:在求解过程中,要确保(a,p)=1,(b,p) = 1,也就是说要将a,b包含的素数p全部除去,并分别统计C(n,m)中分子分母包含p的个数。若分子中的p个数大于分母,直接输出0,相等则应用拓展欧几里得。不会出现分子中p的个数小于分母中p的个数的情况。
代码如下:
#include <stdio.h>
__int64 extgcd(__int64 a,__int64 b,__int64&x,__int64&y)
{
__int64 d,t;
if(b==0)
{
x = 1;
y = 0;
return a;
}
d = extgcd(b,a%b,x,y);
t = x;
x = y;
y = t-a/b*y;
return d;
}
__int64 mod(__int64 a,__int64 b,__int64 p,__int64& count)
{
__int64 res = 1;
__int64 i,t;
for(i = a;i<=b;i++)
{
if(i%p==0)
{
t = i;
while(t%p==0)
{
t/=p;
count++;
}
res = (res*t)%p;
}
else
res = (res*i)%p;
}
return res;
}
int main()
{
int T;
__int64 n,m,p;
__int64 a,b,x,y;
__int64 count1,count2;
scanf("%d",&T);
while(T--)
{
scanf("%I64d%I64d%I64d",&n,&m,&p);
count1 = count2 = 0;
b = mod(1,m,p,count1);
a = mod(n-m+1,n,p,count2);
if(count2>count1)
printf("0\n");
else
{
extgcd(b,p,x,y);
x*=a;
x = x%p;
if(x<0)
x+=p;
printf("%I64d\n",x);
}
}
return 0;
}
这方面比较好的总结:http://www.earthson.net/