Problem 2020 组合
Accept: 1320 Submit: 3180
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem 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
25 2 35 2 61
Sample Output
110
思路:模数是素数,Lucas定理,需要注意的是P很大,求C的时候要一步一步求
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <cmath>
#include <vector>
#define max_ 1000010
#define inf 0x3f3f3f3f
#define ll long long
#define les 1e-8
#define mod 9901
using namespace std;
ll n,m,p;
ll fpow(ll a,ll b)
{
ll tmp=a;
ll ans=1;
while(b)
{
if(b&1)
ans=(ans*tmp)%p;
tmp=(tmp*tmp)%p;
b/=2;
}
return ans;
}
ll C(ll n,ll m)
{
ll ans=1;
for(int i=1;i<=m;i++)
{
ll a=(n-m+i)%p;
ll b=i%p;
ans=(ans*(a*fpow(b,p-2)%p))%p;
}
return ans;
}
ll lucas(ll n,ll m)
{
if(m==0)
return 1;
return C(n%p,m%p)*lucas(n/p,m/p)%p;
}
int main(int argc, char const *argv[]) {
int t;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld%lld",&n,&m,&p);
printf("%lld\n",lucas(n,m) );
}
return 0;
}