数学知识——求组合数

就是求 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=Ca1b+Ca1b1
    当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%pCa/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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

up-to-star

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值