Calculating the factorial of a number involves multiplying all integers from 1 up to that number. Here's a Python program that calculates the factorial of a given number using both iterative and recursive approaches:
- Iterative Approach:
def factorial_iterative(n): factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
- Recursive Approach:
def factorial_recursive(n): # Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: factorial of n is n times factorial of (n-1)
else:
return n * factorial_recursive(n - 1)
Example Usage:
You can test the factorial functions with different values of n
:
num = 5
# Using iterative approach
factorial_iter = factorial_iterative(num)
print(f"Factorial of {num} (iterative): {factorial_iter}")
# Using recursive approach
factorial_rec = factorial_recursive(num)
print(f"Factorial of {num} (recursive): {factorial_rec}")
Explanation:
Iterative Approach (
factorial_iterative
function):- Initialize
factorial
to 1. - Use a loop to multiply
factorial
by each integer from 1 ton
. - Return the final value of
factorial
.
- Initialize
Recursive Approach (
factorial_recursive
function):- Base case: if
n
is 0 or 1, return 1 (since0! = 1
and1! = 1
). - Recursive case: multiply
n
by the factorial of(n-1)
untiln
reaches the base case.
- Base case: if
Both approaches are valid for calculating the factorial of a number. The recursive approach is more concise but might encounter recursion depth limitations for very large values of n
. The iterative approach avoids this issue and is generally more straightforward for this particular problem.