C++排列与组合算法详解

upd 2023/6/3:

本文已经发布进阶版,代码效率比此篇高,有需求的读者可以来阅读

【C++】 排列与组合算法详解(进阶篇)icon-default.png?t=N7T8https://blog.csdn.net/xingchen_2008/article/details/130782915


嘿!好久不见……

今天我又来 水文章 发文章了

今天来介绍一下非常垃圾排列组合算法

声明:本篇文章含有手残作者画的图,大家不要介意(*_*)

学过数学的都知道,组合用 C 表示,排列用 P 或 A 表示

所谓组合,就是在 x 个东西中无顺序地拿 y 个东西 (x\ge y),所有不重不漏的情况的个数

如:

用算术方法的话,就是

C_{4}^{2}=\frac{4\times 3}{2\times 1}=\frac{12}{2}=6

同理,

A_{4}^{2}=4 \times 3=12

我们可以继而推导出组合的一般公式:(! 代表阶乘)

C _{x}^{y}=\frac{x!}{(x-y)! \times y!}

以及排列的一般公式:

A_{x}^{y}=\frac{x!}{y!}

先放个算阶乘的代码:

int fact(int x)//阶乘代码
{
    int res = 1;//返回值变量
    for (int i = x; i; i -- )//用for实现逐次减一
        res *= i;//乘入返回值变量
    return res;//返回
}

再用代码实现排列组合:

int C(int x, int y)//定义组合函数
{
    int ret;
    ret = fact(x) / fact(x - y) / fact(y);//公式
    return ret;
}
int A(int x, int y)//定义排列函数
{
    int ret;
    ret = fact(x) / fact(y);//公式
    return ret;
}

完整代码

#include <iostream>
#define int long long

using namespace std;

int fact(int x)
{
    int res = 1;
    for (int i = x; i; i -- )
        res *= i;
    return res;
}

int C(int x, int y)
{
    int ret;
    ret = fact(x) / fact(x - y) / fact(y);
    return ret;
}

int A(int x, int y)
{
    int ret;
    ret = fact(x) / fact(y);
    return ret;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

	int a, b;
	cin >> a >> b;
	cout << "组合:" << C(a, b) << endl;
	cout << "排列:" << A(a, b) << endl;
	return 0;
}

最终效果

本期的 \text{H}_2\text{O} 文章就到这里了,点个赞,点个关注 ,感谢你们~

  • 18
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星河依旧长明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值