Using the counter
Multiply instead of add, and start the box at the right number. About 8 minutes.
Multiply them all
Last time each pass added the counter to a total. A loop can do any job with the counter, and multiplying is just as common. The factorial of 5 means 5 times 4 times 3 times 2 times 1, and we write it 5!.
The pattern is the same: make a box before the loop, then update it on each pass. Only the update changes. Now it multiplies the box by the counter, instead of adding to it.
product = 1
for i in range(1, 6):
product = product * i- i
- 1
- product
- 1
The product starts at 1. Pass one multiplies it by 1, so it stays 1.
Which number to start from
The starting number matters. A running total starts at 0, because adding zero changes nothing. A running product must start at 1, because multiplying by 1 changes nothing.
Start a product at 0 and every pass multiplies zero by something, so the answer stays 0 forever. Ask yourself: what value can I start with that doesn't change the result? That is the right starting number.
A running product starts at 0 and the loop multiplies it by each number from 1 to 5. What is the final answer?
- A0
- B120
- C15
Show the answer
0. Zero times anything is zero, so the product never gets off the ground.
Factorial
The factorial of n is 1 × 2 × 3 × … × n. The factorial of 0 is 1. Return the factorial of n. It grows very fast, so the result is a long.
n = 5 → 120
0 ≤ n ≤ 18