题意
输出 Cmn%∏i=1ppiCnm%∏i=1ppi 的值。
1≤n,m≤10181≤n,m≤1018
1≤k≤101≤k≤10
∏i=1ppi≤1018∏i=1ppi≤1018 且 1≤pi≤1051≤pi≤105
思路
LucasLucas 定理与 CRTCRT 结合的模板题,其中分成小质数分别取模合并出大数的模,这种方法值得借鉴。
LucasLucas 定理内容:
对于质数 PP ,有 。
证明:
设 n/P=s,m/P=t,n%P=u,m%P=vn/P=s,m/P=t,n%P=u,m%P=v
则原题化为 Cmn≡Cts×Cvu(modm)Cnm≡Cst×Cuv(modm)
构造二项式 (1+x)n(1+x)n
(1+x)n(1+x)n ①
≡(1+x)sP+u≡(1+x)sP+u
≡((1+x)P)s×(1+x)u≡((1+x)P)s×(1+x)u
≡(1+x)s×(1+x)u≡(1+x)s×(1+x)u (费马小定理)
≡(1+xP)s×(1+x)u②≡(1+xP)s×(1+x)u②(modP)(modP)
而幂为 mm 那一项的系数①项中是 ,②项中是Cts×CvuCst×Cuv。
两者相等,得证。
代码
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
typedef long long LL;
using namespace std;
LL fac[100003],invfac[100003];
struct CRT
{
LL A,P;
LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
void exgcd(LL a,LL b,LL &x,LL &y)
{
if(!b){x=1,y=0;return;}
exgcd(b,a%b,y,x);y-=a/b*x;
return;
}
LL Exgcd(LL A,LL B,LL C)
{
LL k1,k2,g=gcd(A,B);
A/=g,B/=g,C/=g;
exgcd(A,B,k1,k2);
return (k1*C%B+B)%B;
}
void kase_insert(CRT _)
{
LL res=Exgcd(P,_.P,_.A-A);
A+=res*P;
P=P/gcd(P,_.P)*_.P;
return;
}
};
LL Pow(LL a,LL p,LL P)
{
LL res=1;
while(p)
{
if(p&1)(res*=a)%=P;
(a*=a)%=P;
p>>=1;
}
return res;
}
void init(LL P)
{
LL f=1;
FOR(i,0,P-1)
{
fac[i]=f;
(f*=i+1)%=P;
}
invfac[P-1]=Pow(fac[P-1],P-2,P);
DOR(i,P-2,0)invfac[i]=invfac[i+1]*(i+1)%P;
return;
}
LL C(LL n,LL m,LL P){return n<m?0:fac[n]*invfac[n-m]%P*invfac[m]%P;}
LL Lucas(LL n,LL m,LL P){return m?Lucas(n/P,m/P,P)*C(n%P,m%P,P)%P:1;}
int main()
{
int T,k;LL n,m,P;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld%d",&n,&m,&k);
CRT sum;
FOR(i,1,k)
{
scanf("%lld",&P);
init(P);
if(i==1)sum=(CRT){Lucas(n,m,P),P};
else sum.kase_insert((CRT){Lucas(n,m,P),P});
}
printf("%lld\n",sum.A);
}
return 0;
}