題意:輸出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/