码迷,mamicode.com
首页 > 其他好文 > 详细

FZU 2020-组合(Lucas定理+逆元解决大组合数求模)

时间:2015-08-28 17:43:47      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:c语言   lucas定理   逆元   

题目地址:FZU 2020
题意:求C(n,m)%p的值(1 <= m <= n <= 10^9, m <= 10^4, m < p < 10^9, p是素数)。
思路:
对于技术分享技术分享并且p是素数,我们一般采用Lucas定理来解。
1).Lucas定理是用来求 C(n,m) mod p的值,p是素数。其描述为:
如果
技术分享
那么得到
技术分享

Lucas(n,m,p)=C(n%p,m%p)* Lucas(n/p,m/p,p)
Lucas(n,0,p)=1;
2).对于大组合数求模C(N,M)%P=N! / (M! * (N-M)! ) % mod
=( N-M+i )! / M!*(i>=1&&i<=M)。然后根据乘法逆元将除法变成乘法即可。

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <bitset>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef __int64 LL;
const int inf=0x3f3f3f3f;
const double pi= acos(-1.0);
const double esp=1e-6;
using namespace std;
LL n,m,mod;
LL modxp(LL a,LL b)
{
    LL res=1;
    while(b>0) {
        if(b&1)
            res=res*a%mod;
        b=b>>1;
        a=a*a%mod;
    }
    return res;
}

LL C(LL n, LL m)
{
    if(m>n) return 0;
    LL ans=1;
    for(int i=1; i<=m; i++) {
        LL a=(n+i-m)%mod;
        LL b=i%mod;
        ans=ans*(a*modxp(b, mod-2)%mod)%mod;
    }
    return ans;
}
LL Lucas(LL n,LL m)
{
    if(m==0) return 1;
    return C(n%mod,m%mod)*Lucas(n/mod,m/mod)%mod;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--) {
        scanf("%lld %lld %lld",&n,&m,&mod);
        printf("%lld\n",Lucas(n,m));
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

FZU 2020-组合(Lucas定理+逆元解决大组合数求模)

标签:c语言   lucas定理   逆元   

原文地址:http://blog.csdn.net/u013486414/article/details/48053603

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!