Challenge: Handshakes, Fast
Completed
At a party of n people, everyone shakes hands with everyone else once. Print the number of handshakes using an O(1) formula – n can be a billion, so a double loop is far too slow. Watch out for overflow!
Input
One whole number n (1 ≤ n ≤ 109).
Output
The number of handshakes.
Example
Input
4
Output
6
Editor
C++
Hints
Each person shakes n - 1 hands, but that counts every handshake twice.
Store n in a long long before multiplying.
Solution explanation
n × (n − 1) / 2 in one step. With n = 10⁹ the product is about 10¹⁸, which fits in a long long.
Show solution
#include <iostream>
using namespace std;
int main() {
long long n;
cin >> n;
cout << n * (n - 1) / 2 << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module