Factorial definition
- Algorithms course
- Beginner
- Lesson 45/80
- 4 min
n! = n * (n-1) * ... * 1 and 0! = 1.
Factorial definition
Factorial is the product of all integers from 1 to n, denoted n!. For example, 5! = 120.
0! is defined as 1. It is computed as n! = n * (n-1) * ... * 1. Factorial is used in permutation and combination calculations.
Recursive definition
Factorial's recursive definition: 0! = 1, n! = n * (n-1)!. This naturally solves factorial with recursion.
The base case is 0! = 1. The recursive step is n * (n-1)!. Each call decreases n and eventually reaches 0.
Practice Recursive factorial
Write factorial(n). If n=0 return 1, else n * factorial(n-1). Print 120 with print(factorial(5)).
Starter code
def factorial(n):
# Compute factorialSample solution
def factorial(n):
# Compute factorial
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))Expected output
120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is 5!?
- 20
- 100
- 120
- 25 Correct answer
Explanation: 5! = 120.
2 Base value
0! = ____
0! = 1
Explanation: 1 is right.
3 Factorial definition: match the terms
| Term | Meaning |
|---|---|
n! |
n*(n-1)! |
0! |
1 |
5! |
120 |
3! |
6 |