组合数3 - lucas a、b较大的组合数

C_{a}^{b} = C_{a/p}^{b/p}* C_{a\%p}^{b\%p}

复杂度\log _{p}N *p *logp,约等于plogp

#include
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define endl '\n'
 
using namespace std;
 
typedef pair PII;
typedef long long ll;
typedef long double ld;

ll a, b, mod;

ll qmi(ll a, ll k)
{
	ll res = 1;
	while(k)
	{
		if(k & 1)res = res * a % mod;
		a = a * a % mod;
		k >>= 1;
	}
	return res;
}

int C(int a, int b)
{
	ll res = 1;
	for(int i = a, j = 1; j <= b; i --, j ++)
	{
		res = res * i % mod;
		res = res * qmi(j, mod - 2) % mod;
	}
	return res;
}

int lucas(ll a, ll b)
{
	if(a < mod && b < mod)return C(a, b);
	return (ll)lucas(a / mod, b / mod) * lucas(a % mod, b % mod) % mod;
}

inline void solve()
{
	cin >> a >> b >> mod;
	cout << lucas(a, b) << endl;
}

int main()
{
	IOS
	int _;
	cin >> _;
	while(_ --)
	{
		solve();
	}
	
	return 0;
}

你可能感兴趣的:(模板,c++,算法,组合数)