求组合数的三种方法

 

 

#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 @ 2023-04-14 17:59  艾鑫4646  阅读(35)  评论(0编辑  收藏  举报