组合数
第一种:递推O(n^2)
void init()
{
for(int i=0;i<M;i++)
{
for(int j=0;j<=i;j++)
{
if(!j) a[i][j]=1;
else a[i][j]=(a[i-1][j]+a[i-1][j-1])%mod;
}
}
}
第二种:逆元 O(nlogn)
#include <iostream>
using namespace std;
const int N=1e5+1003;
typedef long long LL ;
const int mod=1e9+7;
int fact[N],infact[N];
LL mul(int a,int b,int c)
{
LL ans=1;
while(b)
{
if(b&1) ans=ans*a%mod;
a=(LL)a*a%mod;
b>>=1;
}
return ans;
}
void init()
{
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]*mul(i,mod-2,mod)%mod;
}
return ;
}
int main()
{
int t;
cin >> t;
init();
while(t--)
{
int a,b;
cin >> a >> b;
cout << (((LL)fact[a]*infact[b])%mod*infact[a-b])%mod << endl;
}
return 0;
}
第三种:Lucas定理
#include <iostream>
using namespace std;
typedef long long LL;
LL mul(LL a,LL b,LL c)
{
LL res=1;
while(b)
{
if(b&1) res=(res*a)%c;
a=a*a%c;
b>>=1;
}
return res;
}
LL C(LL a,LL b,LL c)
{
LL res=1;
for(int i=a,j=1;j<=b;j++,i--)
{
res=(res*i)%c;
res=(res*mul(j,c-2,c))%c;
}
return res;
}
LL lucas(LL a,LL b,LL c)
{
if(a<c&&b<c) return C(a,b,c)%c;
return (C(a%c,b%c,c)*lucas(a/c,b/c,c))%c;
}
int main()
{
int n;
cin >> n;
while(n--)
{
LL a,b,c;
cin >> a >> b >> c;
cout << lucas(a,b,c)%c << endl;
}
return 0;
}
第四种 :高精度
#include<iostream>
#include<vector>
using namespace std;
const int N=1e5;
int ans[N],sum[N];
bool st[N];
int a,b,cnt;
void get_prices(int d)
{
for(int i=2;i<=d;i++)
{
if(!st[i]) ans[cnt++]=i;
for(int j=0;ans[j]<=d/i;j++)
{
st[ans[j]*i]=true;
if(i%ans[j]==0) break;
}
}
}
int get(int x,int y)
{
int res=0;
while(x)
{
res+=x/y;
x/=y;
}
return res;
}
vector<int> mul(vector<int>&res,int b)
{
vector<int>c;
int t=0;
for(int i=0;i<res.size();i++)
{
t+=res[i]*b;
c.push_back(t%10);
t/=10;
}
while(t)
{
c.push_back(t%10);
t=t/10;
}
return c;
}
int main()
{
cin >> a >> b;
get_prices(a);
for(int i=0;i<cnt;i++)
{
int p=ans[i];
sum[i]=get(a,ans[i])-get(b,ans[i])-get(a-b,p);
}
vector<int> res;
res.push_back(1);
for(int i=0;i<cnt;i++)
{
for(int j=1;j<=sum[i];j++)
{
res=mul(res,ans[i]);
}
}
for(int i=res.size()-1;i>=0;i--)
{
cout << res[i] ;
}
return 0;
}