Example output
**Problem Statement:**
Design a Python program that computes the factorial of a given non-negative integer provided by the user.
**Specific Requirement:**
Ensure the program handles edge cases gracefully, including input validation to ensure the user inputs a non-negative integer. If the input is invalid, the program should display an informative error message guiding the user to enter a valid input.
**Optimization Aspect:**
Optimize the program for performance by implementing an iterative approach to calculate the factorial, avoiding unnecessary function calls and maximizing efficiency.
**Code Solution:**
```python
def factorial_iterative(n):
"""
Calculate the factorial of a non-negative integer using an iterative approach.
Parameters:
n (int): Non-negative integer input.
Returns:
int: Factorial of the input integer.
"""
result = 1
for i in range(1, n + 1):
result *= i
return result
def factorial_recursive(n):
"""
Calculate the factorial of a non-negative integer using recursion.
Parameters:
n (int): Non-negative integer input.
Returns:
int: Factorial of the input integer.
"""
if n == 0:
return 1
else:
return n * factorial_recursive(n - 1)
def calculate_factorial():
"""
Prompt the user to enter a non-negative integer and compute its factorial.
Returns:
int: Factorial of the user input.
"""
while True:
try:
num = int(input("Enter a non-negative integer: "))
if num < 0:
raise ValueError("Input must be a non-negative integer.")
return num
except ValueError:
print("Invalid input. Please enter a non-negative integer.")
def main():
"""
Main function to execute the program.
"""
num = calculate_factorial()
result_iterative = factorial_iterative(num)
result_recursive = factorial_recursive(num)
print(f"Iterative factorial of {num} is: {result_iterative}")
print(f"Recursive factorial of {num} is: {result_recursive}")
if __name__ == "__main__":
main()
```
This Python program provides two functions for calculating the factorial of a non-negative integer: `factorial_iterative` and `factorial_recursive`. It also includes a function `calculate_factorial` to handle user input and ensure it's a non-negative integer. The program is optimized for performance by providing both iterative and recursive solutions, allowing users to compare their efficiency. Additionally, it incorporates error handling to guide users in case of invalid inputs.