组合
Time Limit: 1000MS
Memory Limit: 32768KB
64bit IO Format: %I64d & %I64u
Description
给出组合数C(n,m), 表示从n个元素中选出m个元素的方案数。例如C(5,2) = 10, C(4,2) = 6.可是当n,m比较大的时候,C(n,m)很大!于是xiaobo希望你输出 C(n,m) mod p的值!
Input
输入数据第一行是一个正整数T,表示数据组数 (T <= 100) 接下来是T组数据,每组数据有3个正整数 n, m, p (1 <= m <= n <= 10^9, m <= 10^4, m < p < 10^9, p是素数)
Output
对于每组数据,输出一个正整数,表示C(n,m) mod p的结果。
Sample Input
2
5 2 3
5 2 61
Sample Output
1
10
就是求较大的组合数,用杨辉三角一定会爆
又p是素数,可以用Lucas定理, 并用费马小定理求逆元
注意在求C(n,m) 时, n < m 返回 0
并且如果 n,m 较小时可以预处理阶乘来提高速度
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<iomanip>
#include<ctime>
#include<climits>
#include<cctype>
#include<algorithm>
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
#define smax(x,tmp) x=max((x),(tmp))
#define smin(x,tmp) x=min((x),(tmp))
#define maxx(x1,x2,x3) max(max(x1,x2),x3)
#define minn(x1,x2,x3) min(min(x1,x2),x3)
const int INF=0x3f3f3f3f;
typedef long long LL;
LL quick_mod(LL a,LL p,LL mod)
{
if(p == 0) return 1;
if(p == 1) return a % mod;
LL tmp = quick_mod(a,p/2,mod);
if(p & 1ll) return tmp * tmp % mod * a % mod;
else return tmp * tmp % mod;
}
LL C(LL n,LL m,LL mod)
{
if(n < m) return 0ll;
if(m > (n>>1)) m = n - m;
if(m == 0) return 1ll;
LL ans = 1ll;
for(int i=1;i<=m;i++)
{
LL a = (n - i + 1) % mod;
LL b = i % mod;
ans = ans * (a * quick_mod(b,mod-2,mod) % mod) % mod;
}
return ans;
}
LL Lucas(LL n,LL m,LL mod)
{
if(m == 0ll) return 1ll;
return C(n%mod,m%mod,mod) * Lucas(n/mod,m/mod,mod) % mod;
}
int main()
{
freopen("lucas.in","r",stdin);
freopen("lucas.out","w",stdout);
int q;
scanf("%d",&q);
while(q--)
{
LL n,m,p;
scanf(AUTO AUTO AUTO,&n,&m,&p);
printf(AUTO"\n",Lucas(n,m,p));
}
return 0;
}