Maximum Number Of Handshakes In Java Program
This article explores how to calculate the maximum number of handshakes possible among a group of people using a Java program. You will learn the mathematical formula behind this common problem and how to implement it.
Problem Statement
Imagine a gathering where everyone shakes hands with everyone else exactly once. Given a certain number of people, the challenge is to determine the total number of handshakes that occur. This is a classic combinatorial problem with practical applications in networking, social dynamics, and graph theory.
Example
If there are 3 people (A, B, C), the handshakes would be:
- A-B
- A-C
- B-C
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java basics: Variables, data types, input/output, and basic arithmetic operations.
- Mathematical concepts: Simple combinatorics, specifically combinations.
Use Cases or Case Studies
- Event Planning: Estimating social interactions at a conference or party.
- Network Design: Understanding connections in a fully connected network (e.g., peer-to-peer systems).
- Graph Theory: Representing complete graphs where each node is connected to every other node.
- Team Building Exercises: A simple problem to illustrate combinatorial thinking.
Solution Approaches
Approach 1: Using the Combinatorial Formula
This approach directly applies the mathematical formula for combinations.
- One-line summary: Calculates handshakes using the "n choose 2" formula: n * (n - 1) / 2.
// Maximum Handshakes Calculator
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter the number of people
System.out.print("Enter the number of people: ");
// Step 3: Read the number of people from the user
int numberOfPeople = scanner.nextInt();
// Step 4: Validate input to ensure it's non-negative
if (numberOfPeople < 0) {
System.out.println("Number of people cannot be negative.");
} else {
// Step 5: Calculate the maximum number of handshakes using the formula
// The formula is n * (n - 1) / 2, where n is the number of people.
// This represents "n choose 2" combinations.
long maxHandshakes = (long) numberOfPeople * (numberOfPeople - 1) / 2;
// Step 6: Print the result
System.out.println("Maximum number of handshakes: " + maxHandshakes);
}
// Step 7: Close the scanner to prevent resource leaks
scanner.close();
}
}
Sample Output:
Enter the number of people: 5
Maximum number of handshakes: 10
Stepwise Explanation:
- Initialize Scanner: A
Scannerobject is created to read input from the console. - Prompt User: The program asks the user to enter the number of people.
- Read Input: The
nextInt()method reads the integer value entered by the user. - Validate Input: It checks if the entered number is negative. Handshakes cannot be negative.
- Calculate Handshakes: The core calculation uses the formula
n * (n - 1) / 2.
-
numberOfPeople * (numberOfPeople - 1): This calculates the number of ordered pairs (person A shakes person B's hand, and person B shakes person A's hand are counted as two distinct events). -
/ 2: We divide by 2 because each handshake involves two people, and the order doesn't matter (A-B is the same as B-A). - Casting to
long: For a large number of people, the intermediate productnumberOfPeople * (numberOfPeople - 1)might exceed the maximum value of anint. Casting tolongprevents potential overflow.
- Print Result: The calculated maximum number of handshakes is displayed.
- Close Scanner: The
scanner.close()method is called to release system resources.
Approach 2: Iterative Summation (Less Efficient but Illustrative)
This approach simulates the process by summing handshakes for each person.
- One-line summary: Iteratively sums
(n-1) + (n-2) + ... + 1handshakes.
// Maximum Handshakes Calculator (Iterative)
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of people: ");
int numberOfPeople = scanner.nextInt();
if (numberOfPeople < 0) {
System.out.println("Number of people cannot be negative.");
} else if (numberOfPeople <= 1) { // 0 or 1 person results in 0 handshakes
System.out.println("Maximum number of handshakes: 0");
} else {
long maxHandshakes = 0;
// The first person shakes hands with (n-1) others.
// The second person shakes hands with (n-2) new others (excluding the first).
// ... and so on, until the last person has no new hands to shake.
for (int i = 1; i < numberOfPeople; i++) {
maxHandshakes += i;
}
System.out.println("Maximum number of handshakes: " + maxHandshakes);
}
scanner.close();
}
}
Sample Output:
Enter the number of people: 5
Maximum number of handshakes: 10
Stepwise Explanation:
- Input and Validation: Similar to Approach 1, input is taken and validated. Special handling for 0 or 1 person is added, as they result in 0 handshakes.
- Initialize
maxHandshakes: Alongvariable is initialized to 0 to store the total. - Iterate and Sum:
- The loop runs from
i = 1up tonumberOfPeople - 1. - In each iteration,
irepresents the number of *