# hdu 3037 Saving Beans （Lucas）

xiaoxiao2021-02-28  11

## Problem Description

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.

2 1 2 5 2 1 5

3 3

## 代码

#include <cstdio> #include <cstring> #include <algorithm> #define ll long long using namespace std; ll t, n, m, p; ll exgcd(ll a, ll b, ll &x, ll &y) { if(! b) { x = 1, y = 0; return a; } ll xx, yy; ll r = exgcd(b, a % b, xx, yy); x = yy; y = xx - (a / b) * yy; return r; } ll inverse(ll a, ll m) { ll d, x, y; d = exgcd(a, m, x, y); return (x % m + m) % m; } ll mul(ll a) { ll sum = 1; for(ll i = a; i >= 2; i --) sum = sum * i % p; return sum % p; } ll c(ll n, ll m) { if(m > n) return 0; ll x = mul(m), y = mul(n - m); ll z = x * y % p; z = inverse(z, p); ll ans = (mul(n) % p * (z % p)) % p; return ans; } ll lucas(ll n, ll m) { if(m > n) return 0; if(n / p <= 1) return c(n % p, m % p) % p; return ((lucas(n / p, m / p) % p) * (c(n % p, m % p) % p)) % p; } int main() { scanf("%lld", &t); while(t --) { scanf("%lld %lld %lld", &n, &m, &p); printf("%lld\n", lucas(n + m, m)); } return 0; }