FJNUOJ

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值