Write a recursive and an iterative factorial and confirm they agree for 0 to 10.
def fact_rec(n):
return 1 if n <= 1 else n * fact_rec(n - 1)
def fact_loop(n):
result = 1
for k in range(2, n + 1):
result *= k
return result
print([fact_rec(n) for n in range(8)])
print(all(fact_rec(n) == fact_loop(n) for n in range(11)), fact_rec(10))
[1, 1, 2, 6, 24, 120, 720, 5040] True 3628800
Both follow n! = n × (n − 1)!; the recursive version mirrors the maths, the loop avoids the call stack.