组合数算法

 直接暴力打表:

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值