Saving Beans
Although winter is far away, squirrels have to work day and night to save beans. They need plenty of food to get through those long cold days. After some time the squirrel family thinks that they have to solve a problem. They suppose that they will save beans in n different trees. However, since the food is not sufficient nowadays, they will get no more than m beans. They want to know that how many ways there are to save no more than m beans (they are the same) in n trees.
Now they turn to you for help, you should give them the answer. The result may be extremely huge; you should output the result modulo p, because squirrels can’t recognize large numbers.
Input
The first line contains one integer T, means the number of cases.
Then followed T lines, each line contains three integers n, m, p, means that squirrels will save no more than m same beans in n different trees, 1 <= n, m <= 1000000000, 1 < p < 100000 and p is guaranteed to be a prime.
Output
You should output the answer modulo p.
Sample Input
2 1 2 5 2 1 5
Sample Output
3 3
这个由隔板法得到答案是
但是这里的 n ,m 的值太大了,直接算会T,所以用Lucas定理,取模再运算这个组合数。
Lucas内容:
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
ll f[maxn];
ll quickpow(ll a,ll b,ll mod)
{
ll ans=1;
while(b)
{
if(b&1) ans=(ans*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return ans;
}
ll n,m,p;
void init()
{
f[0]=1;
for(int i=1;i<=p;++i)
f[i]=(f[i-1]*i)%p;
}
ll Lucas(ll n,ll m,ll p)
{
ll res=1;
while(n&&m)
{
ll a=n%p;
ll b=m%p;
if(a<b) return 0;
res=(res*f[a]*quickpow((f[b]*f[a-b])%p,p-2,p))%p;
n/=p;
m/=p;
}
return res;
}
int main()
{
int t;
cin>>t;
while(t--)
{
scanf("%lld%lld%lld",&n,&m,&p);
init();
long long ans=Lucas(n+m,m,p);
printf("%lld\n",ans);
}
}