Retour aux défis
Facile 0 résolus 0 % de réussite

Count Handshakes

Count handshakes when every pair of people shakes hands once.

Ce que vous allez apprendre

  • Count pairs with n × (n - 1) / 2
  • Reason about counting each pair once
  • Replace a loop with a formula

Problème

Afficher la traduction

Every person shakes hands once with every other person. A handshake between A and B is the same event as one between B and A. Nobody shakes their own hand.

Implement handshake_count(people).

Input

people: The number of people.

Output

Return the total number of distinct handshakes.

Contraintes

0 ≤ people ≤ 1,000,000,000. The answer fits a signed 64-bit integer.

Exemples

Exemple 1
Entrée :
people = 4

Sortie attendue :
expected = 6
Entrée :
long long people = 4;

Sortie attendue :
long long expected = 6;
Entrée :
long people = 4;

Sortie attendue :
long expected = 6;

Explication

The pairs are AB, AC, AD, BC, BD, and CD: six handshakes.

Exemple 2
Entrée :
people = 1

Sortie attendue :
expected = 0
Entrée :
long long people = 1;

Sortie attendue :
long long expected = 0;
Entrée :
long people = 1;

Sortie attendue :
long expected = 0;

Explication

One person has nobody else to greet.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Each handshake is just an unordered pair of distinct people.

Indice 2

Count how many pairs can be formed from all people without double-counting.

Indice 3

Be careful that zero or one person means no handshakes at all.

Complexité attendue

O(1) time, O(1) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.