#include <iostream>
using namespace std;
// Function to calculate the number of handshakes
int calculateHandshakes(int n) {
// Using the combination formula C(n, 2)
return (n * (n - 1)) / 2;
}
int main() {
int n;
cout << "Enter the number of friends: ";
cin >> n;
// Calculate and output the number of handshakes
cout << "Total handshakes: " << calculateHandshakes(n) << endl;
return 0;
}
### Explanation of the Code
- **Function `calculateHandshakes`**: This function takes an integer `n` and returns the number of handshakes using the combination formula.
- **Main Function**: Reads the input value `n`, calls the `calculateHandshakes` function, and prints the result.
## Complexity Analysis
- **Time Complexity**: O(1) - The calculation involves a constant number of operations.
- **Space Complexity**: O(1) - No additional space is required beyond the input and a few variables.
## Edge Cases
- **Minimum Input**: When `n = 1`, the output should be `0` as there are no other friends to shake hands with.
- **Large Input**: The solution should handle large values of `n` efficiently due to its O(1) complexity.
### Example Edge Cases
1. **Input**: `n = 1`
**Output**: `0`
2. **Input**: `n = 1000000000`
**Output**: `499999999500000000`
## Testing
To test the solution comprehensively, consider the following test cases:
1. Simple cases with small `n` values.
2. Edge cases with `n = 1`.
3. Large values of `n` to ensure the solution handles them efficiently.
## Conclusion
Understanding and solving combinatorial problems like this one is crucial for developing strong problem-solving skills. The optimized solution using the combination formula is efficient and elegant, making it suitable for large inputs.
## Additional Resources
- [Combinatorics and Permutations](https://en.wikipedia.org/wiki/Combinatorics)
- [C++ Documentation](https://en.cppreference.com/w/)
- [LeetCode](https://leetcode.com/) for more practice problems.
By practicing similar problems and understanding the underlying principles, you can improve your problem-solving skills and tackle more complex challenges with confidence.
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