#include<iostream>
#define ll long long
using namespace std;
// x*x^-1%mod == 1
ll exgcd(ll a, ll b, ll &x, ll &y)// ax+by == gcd(a, b)
{
ll res;
if(b == 0)
{
x = 1;
y = 0;
return a;
}
res = exgcd(b,a%b, x, y);
ll tmp = y;
y = x- a/b*y;
x = tmp;
return res;
}
ll mod_reverse(ll a, ll mod)
{
ll x, y, d;
d = exgcd(a, mod, x, y);
if(d == 1)
{
/**大于 0 的通******/
if(x%mod <= 0)return x%mod+mod;
else return x%mod;
}
else return -1ll;//(long long)-1;
}
ll C(ll n, ll m, ll mod)
{
m = min(m, n-m);
ll res = 1;
for(ll i = m;i >= 1;i--)
{
res = (res*(n-i+1)%mod * mod_reverse(i, mod)%mod)%mod;
}
return res;
}
int main()
{
int T;
cin>>T;
ll n, m , mod;
while(T--)
{
cin>>n>>m>>mod;
cout<<C(n, m, mod)<<endl;
}
}
组合+乘法逆元
最新推荐文章于 2022-05-02 15:12:47 发布