组合数取模

给出组合数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

这题用上逆元和Lucas,Lucas是为了防止n太大,而p有小于n的时候,应该测试数据不够完整,没有p大于n,而n也很大的数据,所以能过,逆元是因为除数不可以取模;

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cmath>
#include<string.h>
#include<algorithm>
#define sf scanf
#define pf printf
#define cl clear()
#define pb push_back
#define mm(a,b) memset((a),(b),sizeof(a))
#include<vector>
int n,m,mod;
const double pi=acos(-1.0);
typedef __int64 ll;
typedef long double ld;
//const ll mod=1e9+7;
using namespace std;
ll niyuan(ll a,ll b)
{
	ll ans=1,bas=a;
	while(b)
	{
		if(b&1) ans=ans*bas%mod;
		bas=bas*bas%mod;
		b>>=1;
	}
	return ans;
}
ll solve(int n,int m)
{
	if(m==0)
	return 0;
	if(m>n-m)
	m=n-m;
	ll up=1,down=1;
	for(int i=1;i<=m;i++)
	{
		up=up*(n-i+1)%mod;
		down=down*i%mod;	
	}
	down=niyuan(down,mod-2);
	return up*down%mod;
}
ll lucas(int a,int b)
{
	if(b==0)return 1;
	return lucas(a/mod,b/mod)*solve(a%mod,b%mod)%mod;
}
int main()
{
	int re;
	cin>>re;
	while(re--)
	{
		cin>>n>>m>>mod;
		cout<<lucas(n,m)<<endl;
	}
	return 0;
} 
原文地址:https://www.cnblogs.com/wzl19981116/p/9353982.html