组合数模板

RDC大佬的组合数模板  不多BB  先粘过来


求C(N,M)%P


N M 很大  P 较小

#include <iostream>  
#include <string.h>  
#include <stdio.h>  
using namespace std;  
typedef long long LL;
const int NICO = 100000+10;
const int MOD  = 99991;
LL f[NICO];  
LL pow(LL a, LL n)
{
    LL ret = 1;
    while(n)
    {
        if(n & 1)
        {
            ret = (ret * a);
            ret %= MOD;
        }
        a = a * a % MOD;
        n >>= 1;
    }
    return ret;
}

LL Lucas(LL a,LL k) 
{  
    LL res = 1;  
    while(a && k)  
    {  
        LL a1 = a % MOD;
        LL b1 = k % MOD;  
        if(a1 < b1) return 0;
        res = res*f[a1]*pow(f[b1]*f[a1-b1]%MOD,MOD-2)%MOD;
        a /= MOD;  
        k /= MOD;  
    }  
    return res;  
}  

void init()  
{  
    f[0] = 1;  
    for(int i=1;i<=MOD;i++) 
    { 
        f[i] = f[i-1]*i%MOD;    
    }
}  
 
LL T, n;
int main()  
{  
    init();
    cout << Lucas(5,2) << endl;
} 


N M 较小  P 很大


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const int P = 1000000007;
LL f[1000001], v[1000001];
LL rp(LL now, int k) 
{
    LL will = 1;
    for (; k; k >>= 1, now *= now, now %= P) 
    {
        if (k & 1) will *= now, will %= P;
    }
    return will;
}
LL C(int n, int m) 
{
    if(n < m) return 0;
    return f[n] * rp(f[m], P - 2) % P * rp(f[n - m], P - 2) % P;
}
void init()
{
    f[0] = 1; v[0] = 1;
    for (int i = 1; i <= 1000000; i++) //1e6以内的组合数
    {
        f[i] = f[i - 1] * i % P;
    }
}
int main() 
{
    init();
    int n, m;
    scanf("%d %d", &n, &m);
    printf("%lld\n", C(m, n));
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值