-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursion.py
More file actions
42 lines (33 loc) · 1.08 KB
/
recursion.py
File metadata and controls
42 lines (33 loc) · 1.08 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
# Recursion — a function that calls itself to solve a problem
# by breaking it into smaller instances of the same problem.
#
# Factorial is the classic example:
# n! = n × (n-1) × (n-2) × ... × 1
# 0! = 1 (base case)
#
# Both iterative and recursive versions produce the same result.
# The recursive version directly mirrors the mathematical definition.
# --- Iterative ---
def factorial_iterative(n):
result = 1
for x in range(1, n + 1):
result *= x
return result
# --- Recursive ---
# Base case: n == 0 or n == 1 → return 1
# Recursive case: n! = n × (n-1)!
def factorial_recursive(n):
if n == 0 or n == 1:
return 1
return n * factorial_recursive(n - 1)
if __name__ == '__main__':
while True:
try:
n = int(input('Enter a non-negative integer: '))
if n < 0:
raise ValueError
break
except ValueError:
print('Incorrect input, try again.')
print(f'{n}! = {factorial_iterative(n)} (iterative)')
print(f'{n}! = {factorial_recursive(n)} (recursive)')