Prompt
Answer
Function to Calculate the Factorial in C++
The following sections outline a C++ function that calculates the factorial of a given non-negative integer. This includes necessary imports, documentation, input validation, and an example of usage.
Necessary Imports
For our task, no additional libraries are required, as the function will only use standard C++ features.
Function Implementation
#include
#include
long long factorial(int n) {
/**
* Calculate the factorial of a non-negative integer.
*
* @param n: A non-negative integer whose factorial is to be computed.
* @return: The factorial of the number as a long long integer.
* @raises std::invalid_argument: If n is negative.
*
* This function uses an iterative approach to compute the factorial efficiently.
*/
// Input validation
if (n < 0) {
throw std::invalid_argument("Factorial is not defined for negative numbers.");
}
long long result = 1; // Start with 1 as the factorial of 0 is also 1
for (int i = 1; i <= n; ++i) {
result *= i; // Multiply result by current number
}
return result;
}
Code Commentary
- Function Documentation: The docstring provides essential information about the parameters, return type, and exceptions.
- Input Validation: A check confirms the input is a non-negative integer. If not, an exception is raised.
- Factorial Calculation: An iterative loop multiplies the current result by each integer from 1 to n, accumulating the result.
- Return Type: The function returns a
long long
type to accommodate large values, given that factorials grow quickly.
Usage Example
Here’s how you can use the factorial
function in a real-world scenario:
int main() {
try {
int number = 5; // Example input
std::cout << "Factorial of " << number << " is " << factorial(number) << std::endl;
number = -1; // Example that raises an exception
std::cout << "Factorial of " << number << " is " << factorial(number) << std::endl;
} catch (const std::invalid_argument &e) {
std::cerr << "Error: " << e.what() << std::endl; // Handle negative input error
}
return 0;
}
Summary
- Purpose: Calculate the factorial of a non-negative integer efficiently.
- Robustness: The function includes input validation to handle invalid inputs gracefully.
- Scalability: The use of
long long
allows for handling larger factorials, but be aware of potential overflow for very large inputs.
This implementation serves as a foundational approach to computing factorials in an efficient and well-documented manner. For further learning, consider exploring courses on the Enterprise DNA Platform, which offer advanced insights into data manipulation and programming techniques.
Description
A robust C++ function to calculate the factorial of a non-negative integer with input validation, efficient iterative computation, and comprehensive documentation for ease of use.