-
Notifications
You must be signed in to change notification settings - Fork 11
Open
Description
The current factorial code examples work well for simple cases, but they could be improved by adding input validation and handling large integers, especially for languages that don’t support big integers natively. Here are some areas for improvement:
1. Input Validation:
• In each example, there’s little or no validation for negative or non-integer inputs. If a user enters a negative number, the recursive functions will either run indefinitely or throw an error.
• For functions using scanf or input directly, it would help to check if the input is positive before starting the calculation.
2. Handling Large Numbers:
• Factorial results grow extremely fast, and for large n values (e.g., 20+), standard integer types may overflow. This is particularly an issue in the C and Java versions since they lack native support for arbitrarily large numbers.
• Adding support for large integers where possible or providing an overflow warning would improve robustness.
Suggested Fixes:
• Add input validation: Ensure each function checks if n is a positive integer. If not, return an error message or handle it gracefully.
• Use big integer libraries (in Java and C) or add a note in the documentation to alert users about possible overflow for large n values.
Python code example :
def recur_factorial(n):
if n == 1:
return n
else:
return n * recur_factorial(n - 1)
num = input("Enter a number: ")
try:
num = int(num)
if num < 0:
print("Factorial does not exist for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
except ValueError:
print("Invalid input: please enter an integer.")
Metadata
Metadata
Assignees
Labels
No labels