组合数求解(Lucas定理)

组合数求解

方法一

直接递推求组合数。
公式: C(a, b) = C(a-1, b) + C(a-1, b-1)
预处理所有的C(a, b)

#include <iostream>
#include <algorithm>

using namespace std;
//C(a, b) 组合数  a!/ b!(a - b)!
//递推
const int MOD = 1e9 + 7 ;
const int N = 2003;
int c[N][N];
void predeal()
{
  c[0][0] = 1;
  for(int a = 1; a < N; a ++)
    for(int j = 0; j <= a; j ++)
      if(!j) c[a][j] = 1;//select zero ,so result is 1;
        else c[a][j] = (c[a - 1][j] + c[a - 1][j - 1]) % MOD;
}

int main()
{
    predeal();
    int n;
    scanf("%d", &n);
    
    while (n --)
    {
       int a, b;
       cin >> a >> b;
       printf("%d\n", c[a][b]);
    }
    return 0;
}

方法二

引入逆元,求解组合数对p的模,p为素数。
C(a, b) 组合数 a!/ b!(a - b)!
形如 A/(B * C * D) mod p ,等价于 (A * B-1 C-1D-1) mod p ,可以递推求解。
上式还等价于 (A * ((B
C
D) % p)-1) % p

#include <iostream>
#include <algorithm>
using namespace std;
//逆元求组合数
typedef long long  LL;
const   int N   =   100010;
const   int mod  =   1e9 + 7;

int fact[N], infact[N];//inverse element
//KSM
int qmi(int a,  int k,  int p)
{
    int res =   1 % p;
    while (k)
    {
        if(k  & 1)  res = (LL)res * a  %  p;
        a=  (LL)a  *  a   %   p;
        k  >>= 1;
    }
    return  res;
}
int main()
{
    int n;
    scanf("%d",&n);
    fact[0] =  infact[0] = 1;
    for (int i = 1; i < N; i++)
    {
        fact[i] = (LL)fact[i-1] * i % mod;//n!  
      infact[i]=(LL)infact[i-1] * qmi(i,mod-2,mod) % mod;
    }
    while (n --)
    {
        int a,  b;
        scanf("%d%d",&a, &b);
 printf("%d\n",(LL)fact[a] * infact[b] % mod *infact[a-b] % mod);
    }
    return 0;
}

方法三

Lucas定理求解
定理: C(a, b) ≡ C(a % p , b % p) * C(a / p, b / p) % p
此方法一般求解模数p是相对较小的质数,a和b均在1018级别
算法实现: 递归;小费马定理

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值