握手次数,每个人只握一次手

2023年 8月 30日 69.8k 0

握手次数,每个人只握一次手

假设你在一个社交聚会中。如果你只握手一次,你能计算出你能做多少次握手吗?这个问题可能让你感到有趣。这个问题可以通过使用排列组合的数学方法来解决。然而,数学运算可能会耗费时间。

在本文中,我们将讨论如何使用C++解决这个问题。我们将探讨不同的方法,包括数学公式、递归和其他组合技术。

输入输出场景

Suppose you have N number of people in a gathering. You want to calculate the number of handshakes possible such that a person shakes hands only once.

Input: N = 16
Output: 120
Input: N = 11
Output: 55

登录后复制

Using the Formula for Handshakes

The formula for finding the number of handshakes in a gathering of N people is −

No. of handshakes = N *(N-1) /2

登录后复制

Each of the N people will shake the hands with (N-1) individuals (excluding the person itself) and the handshakes between two individuals is not counted twice.

For Example, if the number of individuals is 14. Then, number of handshakes are

Handshakes = 14 * (14 - 1)/ 2
= 14 * 13 / 2
= 182/2
= 91

登录后复制

Example

在下面的示例中,我们使用的是计算握手次数的公式。在这里,我们只需使用数学运算符,以聚会上的人数作为输入。

#include
using namespace std;

int count(int N) {
// Formula: N * (N-1) / 2
return (N * (N - 1)) / 2;
}

int main() {
int totalIndividuals= 10;
int numHandshakes = count(totalIndividuals);
std::cout

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论