求组合数的三种方法

 

 

复制代码
#include<bits/stdc++.h>
using namespace std;
const int N=2010,mod=1e9+7;
int c[N][N];
 void inti(){
     for(int i=0;i<N;i++){
         for(int j=0;j<=i;j++){
             if(j==0) c[i][j]=1;
             else 
             {
                 c[i][j]=(c[i-1][j-1]+c[i-1][j])%mod;
             }
         }
     }
 }
int main(){
    int n;
    cin>>n;
    inti();
while(n--){
    int a,b;
    cin>>a>>b;
     printf("%d\n",c[a][b]);
}
    return 0;
}

 
复制代码
复制代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e5+10,mod=1e9+7;
int infact[N],fact[N];
 int qmi(int a, int k, int p)
{
    int res = 1;
    while (k)
    {
        if (k & 1) res = (LL)res * a % p;
        a = (LL)a * a % p;
        k >>= 1;
    }
    return res;
}

int main(){
    int n;
    cin>>n;
     fact[0] = infact[0] = 1;
    for (int i = 1; i < N; i ++ )
    {
        fact[i] = (LL)fact[i - 1] * i % mod;
        infact[i] = (LL)infact[i - 1] * qmi(i, mod - 2, mod) % mod;
    }
    while(n--){
        int a,b;
        cin>>a>>b;
        printf("%d\n", (LL)fact[a] * infact[b] % mod * infact[a - b] % mod);
    }
    return 0;
}

 
复制代码

 

复制代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int p;
int qmi(LL a,int k){
    int res=1;
    while(k){
        if(k&1)  res=(LL)res*a%p;
        a=(LL)a*a%p;
        k>>=1;
    }
    return res;
}
int C(LL a,LL b){
    if(b>a) return 0;
    int res=1;
    for(int i=1,j=a;i<=b;i++,j--){
        res=(LL)res*j%p;
         res = (LL)res * qmi(i, p - 2) % p;
    }
    return res;
}
int lucas(LL a,LL b){
    if(a<p&&b<p) return C(a,b);
    return (LL)C(a%p,b%p)*lucas(a/p,b/p)%p;
}
int main(){
    int n;
    cin>>n;
    while(n--){
        LL a,b;
        cin>>a>>b>>p;
        cout<<lucas(a,b)<<endl;
    }
    return 0;
    }
复制代码

 

posted @   艾鑫4646  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示