📜  查找最大握手次数

📅  最后修改于: 2021-05-04 12:28:48             🧑  作者: Mango

一个房间里有N个人。找到最大数量的握手。考虑到任何两个人都只握手一次的事实。

例子 :

Input : N = 2
Output : 1.
There are only 2 persons in the room. 1 handshake take place.

Input : N = 10
Output : 45.

为了最大程度地增加握手次数,每个人都应该与房间中的每个其他人握手。对于第一人称,将进行N-1次握手。对于第二人称,将有N-1个人可用,但他已经与第一人称握手。因此会有N-2次握手,依此类推。
因此,握手总数= N-1 + N-2 +…。+ 1 + 0,等于((N-1)* N)/ 2
(使用前N个自然数之和的公式)。

下面是此问题的实现。

C++
// C++ program to find maximum number of
// handshakes.
#include
using namespace std;
 
// Calculating the maximum number of handshake
// using derived formula.
int maxHandshake(int n)
{
  return (n * (n - 1))/ 2;
}
 
// Driver Code
int main()
{
  int n = 10;
  cout << maxHandshake(n) <


Java
// Java program to find maximum number of
// handshakes.
 
class GFG
{
    // Calculating the maximum number of
    // handshake using derived formula.
    static int maxHandshake(int n)
    {
        return (n * (n - 1)) / 2;
    }
     
     
    // Driver code
    public static void main (String[] args)
    {
        int n = 10;
        System.out.println( maxHandshake(n));
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python3 program to find maximum
# number of handshakes.
 
# Calculating the maximum number
# of handshake using derived formula.
def maxHandshake(n):
 
    return int((n * (n - 1)) / 2)
 
# Driver Code
n = 10
print(maxHandshake(n))
 
# This code is contributed by Smitha Dinesh Semwal.


C#
// C# program to find maximum number of
// handshakes.
using System;
 
class GFG
{
    // Calculating the maximum number of
    // handshake using derived formula.
    static int maxHandshake(int n)
    {
        return (n * (n - 1)) / 2;
    }
     
     
    // Driver code
    public static void Main ()
    {
        int n = 10;
        Console.Write( maxHandshake(n));
    }
}
 
// This code is contributed by nitin mittal.


PHP


Javascript


输出:

45

时间复杂度: O(1)