public class HandShakes {
public static int countHandShakes(int n) {
// Using the combination formula C(n, 2) = n * (n - 1) / 2
return (n * (n - 1)) / 2;
}
public static void main(String[] args) {
int n = 3; // Example input
System.out.println("Total handshakes: " + countHandShakes(n));
}
}
### Explanation of the Code
- **countHandShakes**: This method takes an integer `n` and returns the number of handshakes using the combination formula.
- **main**: This method demonstrates the usage of `countHandShakes` with an example input.
## Complexity Analysis
- **Time Complexity**: O(1) - The formula calculation is constant time.
- **Space Complexity**: O(1) - No additional space is required.
## Edge Cases
- **n = 1**: Only one person, so no handshakes. The output should be `0`.
- **n = 2**: Two people, one handshake. The output should be `1`.
- **Large n**: The formula handles large values efficiently due to its O(1) complexity.
## Testing
To test the solution comprehensively, consider the following test cases:
1. **Simple Case**: `n = 3` (Expected output: `3`)
2. **Single Person**: `n = 1` (Expected output: `0`)
3. **Two People**: `n = 2` (Expected output: `1`)
4. **Large Number**: `n = 1000000` (Expected output: `499999500000`)
## Conclusion
Understanding and solving combinatorial problems like this one is crucial for developing efficient algorithms. The key takeaway is to recognize the problem as a combination problem and apply the appropriate formula to achieve an optimal solution.
## Additional Resources
- [Combinatorics and Permutations](https://en.wikipedia.org/wiki/Combinatorics)
- [Java Math Library](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html)
- [LeetCode](https://leetcode.com/) for more practice problems.
By practicing such problems, you can enhance your problem-solving skills and prepare for coding interviews effectively.
Our interactive tutorials and AI-assisted learning will help you master problem-solving skills and teach you the algorithms to know for coding interviews.
Start Coding for FREE