Hey everyone! π
Today, we're tackling a classic mathematical problem: Calculating the Factorial.
The Problem
The goal is to write a function that calculates the factorial of a number.
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
Formula: n! = n Γ (n-1) Γ (n-2) Γ ... Γ 1
Special Case: 0! = 1
Example:
-
factorial(5)should return120(because5 Γ 4 Γ 3 Γ 2 Γ 1 = 120) -
factorial(0)should return1
The Solution
Here is the Python implementation using a loop:
def factorial(n):
"""
Calculates the factorial of a number using a loop.
"""
# Base case: 0! and 1! are both 1
if n == 0 or n == 1:
return 1
else:
result = 1
# Loop from 2 up to n
for i in range(2, n + 1):
result *= i
return result
# Test cases
print(factorial(5))
# Output: 120
print(factorial(0))
# Output: 1
print(factorial(7))
# Output: 5040
Code Breakdown
Let's walk through the code line by line:
-
def factorial(n):- Defines a function named
factorialthat takes one parametern(the number to calculate the factorial for).
- Defines a function named
-
if n == 0 or n == 1: return 1- Base case: If
nis0or1, we return1immediately. - This is because
0!is defined as1, and1!is obviously1.
- Base case: If
-
else: result = 1- If
nis greater than1, we initialize a variableresultto1. -
1is the multiplicative identity (multiplying by 1 doesn't change the value), making it a safe starting point.
- If
-
for i in range(2, n + 1):- We start a loop that iterates from
2up ton. -
range(2, n + 1)generates numbers starting from2and stopping beforen + 1, which means it includesn.
- We start a loop that iterates from
-
result *= i- In each iteration, we multiply the current
resultby the loop variablei. - This accumulates the product (
1 * 2 * 3 * ... * n).
- In each iteration, we multiply the current
-
return result- After the loop finishes, we return the final computed factorial value.
Example Walkthrough with factorial(5)
Let's trace what happens when we call factorial(5):
- Check: Is
5equal to0or1? No. - Initialize:
resultstarts at1. - Loop:
iwill take values2,3,4,5.- i = 2:
result= 1 * 2 = 2 - i = 3:
result= 2 * 3 = 6 - i = 4:
result= 6 * 4 = 24 - i = 5:
result= 24 * 5 = 120
- i = 2:
- Return: The loop ends, and the function returns
120.
Happy coding! π»
Top comments (0)