就是求 C a b C_{a}^{b} Cab
- 1、预处理所有C[a][b],用公式
C
a
b
=
C
a
−
1
b
+
C
a
−
1
b
−
1
C_{a}^{b} =C_{a-1}^{b}+C_{a-1}^{b-1}
Cab=Ca−1b+Ca−1b−1
当a,b数据范围较小时适用。
long long C[N][N];
int mod = 1e9+7;
void zuhe(int n){
for(int i=0;i<=n;i++){
for(int j=0;j<=i;j++){
if(!j) C[i][j] = 1;
else C[i][j] = C[i-1][j-1]+C[i-1][j];
}
}
}
- 2、预处理a和b的阶乘
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5+10,mod = 1e9+7;
LL fact[N],infact[N];
int n;
LL qmi(int a,int b,int p){
LL res = 1;
while(b){
if(b&1)res = (LL)(res*a)%p;
b = b>>1;
a = (LL)a*a%p;
}
return res;
}
int main()
{
fact[0] = infact[0] = 1;
for(int i=1;i<N;i++){
if(i==1)fact[i] = infact[i] = 1;
else{
fact[i] = (fact[i-1]*i)%mod;
infact[i] = (infact[i-1]*qmi(i,mod-2,mod))%mod;
}
}
scanf("%d",&n);
int a,b;
while(n--){
scanf("%d%d",&a,&b);
printf("%lld\n",((fact[a]*infact[b])%mod*infact[a-b])%mod);//每乘一次取一次模,防止溢出。
}
return 0;
}
- 3、当a和b巨大时,要用卢卡斯定理
卢卡斯定理: C a b = C a % p b % p ∗ C a / p b / p C_{a}^{b}=C_{a\%p}^{b\%p}*C_{a/p}^{b/p} Cab=Ca%pb%p∗Ca/pb/p
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL a,b,p;
LL qmi(LL a,LL b,LL p){
LL res = 1;
while(b){
if(b&1)res = res*a%p;
a = a*a%p;
b= b>>1;
}
return res;
}
LL C(LL a,LL b){//边循环边求C
LL res = 1;
for(int i=1,j=a;i<=b;i++,j--){
res = res*j%p;
res = res*qmi(i,p-2,p)%p;
}
return res;
}
LL lucas(LL a,LL b){
if(a<p&&b<p) return C(a,b)%p;
else return ((C(a%p,b%p)%p)*(lucas(a/p,b/p))%p)%p;
}
int main()
{
int n;
scanf("%d",&n);
while(n--){
scanf("%lld%lld%lld",&a,&b,&p);
LL res = lucas(a,b);
printf("%lld\n",res);
}
return 0;
}