887. 求组合数 III (lucas定理)

在这里插入图片描述
https://www.acwing.com/problem/content/889/
在这里插入图片描述
在这里插入图片描述
图片摘自:https://www.acwing.com/solution/content/26553/
图片摘自: https://www.acwing.com/solution/content/5244/

这里的求组合数的函数:快速幂是在循环的里边:耗时约 1345 ms

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long int LL;
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,LL p)
{
	if(b>a) return 0;
	
	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,LL p)
{
	if(a<p&&b<p) return C(a,b,p);
	return C(a%p,b%p,p)*lucas(a/p,b/p,p)%p;
} 
int main(void)
{
	int t; cin>>t;
	while(t--)
	{
		LL a,b,p; cin>>a>>b>>p;
		cout<<lucas(a,b,p)<<endl;
	}
	return 0;
}

这里的求组合数的函数:快速幂是在循环的外边:耗时约 80 ms

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long int LL;
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, LL p)
{
    if(b > a) return 0;
    if(b > a - b) b = a - b;
    LL x = 1, y = 1;
    for(int i = 0; i < b; i++)
    {
        x = x * (a - i) % p;
        y = y * (i + 1) % p;
    }
    return x * qmi(y, p - 2, p) % p;
}
LL lucas(LL a,LL b,LL p)
{
	if(a<p&&b<p) return C(a,b,p);
	return C(a%p,b%p,p)*lucas(a/p,b/p,p)%p;
} 
int main(void)
{
	int t; cin>>t;
	while(t--)
	{
		LL a,b,p; cin>>a>>b>>p;
		cout<<lucas(a,b,p)<<endl;
	}
	return 0;
}

快速幂放在外面的方法来自Acwing评论区某位大神。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值