1101: Apple Tree
Time Limit: 1 Sec Memory Limit: 128 MB
64-bit interger IO format: %lld Java class name: Main
Submit Status Discuss
Description
Dog two is the gratest Acmer of FJNU. when he is a little boy, he can calculate some difficult problem. One day they come to a farm where has so many apple trees. Suddenly, he get a idea that how many way to select m apple from the apple trees. He soon got the answer. But the apple trees are so many that he can’t calculate the exact answer. You must help he, the poor Dog two.
Input
Input contains multiple sets of data, a num T on the first line that means the sizes of sets of data. Each group of data is only one line. Each group of data has three numbers n, m, P that there is a total of N apples on apple trees, Dog two want to pick out M apple, the answer % p
PS: 0 <= n <= 10^18,0 <= m <= 10^8,2 <= p <= 100007 and p is a primer
Output
Each group of sample output line answer (remember the answer to the P module)
Sample Input
2
10 2 787
5 1 5
Sample Output
45
0
是一个C(m,n)再取模的过程,用卢卡斯定理
#include "cstring"
#include "iostream"
#include "string.h"
#include "cstdio"
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 100005;
LL fact[maxn];
LL p;
LL quick_pow(LL a, LL k)
{
LL ans = 1;
while(k)
{
if(k & 1) (ans *= a) %= p;
(a *=a) %= p;
k >>= 1;
}
return ans;
}
void Init()
{
fact[0] = 1;
for(int i = 1; i <= p; i ++)
{
fact[i] = fact[i - 1] * i % p;
}
}
LL Inv(LL n)
{
return quick_pow(n, p - 2);
}
LL C(LL n, LL m)
{
if(n < m) return 0;
return fact[n] * Inv(fact[n - m] * fact[m] % p) % p;
}
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 T;
LL n, m;
scanf("%d", &T);
while(T--)
{
scanf("%lld%lld%lld", &n, &m, &p);
Init();
printf("%lld\n", lucas(n, m));
}
return 0;
}