forked from Sbiswas001/Basic-python-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactorial.py
More file actions
83 lines (60 loc) · 1.91 KB
/
factorial.py
File metadata and controls
83 lines (60 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
Factorial Program
This program calculates the factorial of a given number.
Factorial of n (n!) = n * (n-1) * (n-2) * ... * 1
"""
def factorial(n):
"""
Calculate the factorial of a number.
Args:
n (int): A non-negative integer
Returns:
int: The factorial of n
Raises:
ValueError: If n is negative
TypeError: If n is not an integer
"""
if not isinstance(n, int):
raise TypeError("Input must be an integer")
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
if n == 0 or n == 1:
return 1
result = 1
for i in range(2, n + 1):
result *= i
return result
def factorial_recursive(n):
"""
Calculate the factorial of a number using recursion.
Args:
n (int): A non-negative integer
Returns:
int: The factorial of n
Raises:
ValueError: If n is negative
TypeError: If n is not an integer
"""
if not isinstance(n, int):
raise TypeError("Input must be an integer")
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
if n == 0 or n == 1:
return 1
return n * factorial_recursive(n - 1)
if __name__ == "__main__":
# Example usage
print("Factorial Calculator")
print("=" * 40)
try:
num = int(input("Enter a non-negative integer: "))
# Calculate using iterative method
result_iterative = factorial(num)
print(f"\nFactorial of {num} (iterative): {result_iterative}")
# Calculate using recursive method
result_recursive = factorial_recursive(num)
print(f"Factorial of {num} (recursive): {result_recursive}")
except ValueError as e:
print(f"Error: {e}")
except TypeError as e:
print(f"Error: {e}")