直接暴力打表:
ps:如果二维数组在编译器上显示数组太大了,自行修改二维数组大小
//打表
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long int LL;
const int M = 1e9+7;
const int MAXN = 10001;
LL C[MAXN + 1][MAXN + 1];
void Initial()
{
int i, j;
for (i = 0; i <= MAXN; ++i)
{
C[0][i] = 0;
C[i][0] = 1;
}
for (i = 1; i <= MAXN; ++i)
{
for (j = 1; j <= MAXN; ++j)
C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % M;
}
}
int main()
{
Initial();
int t;
scanf("%d", &t);
while (t--)
{
int m, n;
scanf("%lld %lld", &m, &n);
printf("%lld\n", C[m][i]);
}
}
费马小定理加快速幂(g^(MOD-2)=1/g%MOD,将除法问题转化为乘法)
先把阶乘打表预处理一下提高效率
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
const ll mod = 1e9+7;
const ll maxn = 100001;
ll c[maxn];
void init()
{
c[1] = 1;
for (ll i = 2; i <= maxn; i++)
{
c[i] = c[i - 1] * i%mod;
//cout<<c[i]<<endl;
}
}
ll quickmod(ll a, ll b)//计算a^b并且对mod取余
{
ll ans = 1;
while (b)
{
if (b & 1)
{
ans = ans * a%mod;
}
b >>= 1;//相当于b/=2;
a = (a%mod)*(a%mod) % mod;
}
return ans;
}
ll C(ll n, ll m)//计算C(n,m)
{
return c[n] * quickmod(c[m] * c[n - m] % mod, mod - 2) % mod;
}
int main()
{
init();
int t;
scanf("%d", &t);
while (t--)
{
ll m, n;
scanf("%lld %lld", &m, &n);
printf("%lld\n", C(m,n));
}
}
拓展欧几里得:
LL fac[N];
void init()
{
LL i;
fac[0]=1;
for (LL i = 1; i < N; i++)
fac[i] = fac[i - 1] * i % MOD;
}
LL exgcd(LL a, LL b, LL &x, LL &y) {
if (!b) {x = 1; y = 0; return a;}
LL d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
LL inv(LL a, LL n) {
LL x, y;
exgcd(a, n, x, y);
return (x + n) % n;
}
LL C(LL n, LL m) {
return fac[n] * inv(fac[m] * fac[n - m] % MOD, MOD) % MOD;
}
暴力
ll C(int n, int m) {
if (n < m) return 0;
if (n == m) return 1;
ll res = 1;
for(int i = n, j = 1; i >= n - m + 1; i--,j++) res *= i,res /= j;
return res;
}