DSA Factory
Free lessonsProgramming basics · Stage 3 · Loops that count · Step 2

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.

The loop shape stays the same, only the update changes.
In code
product = 1
for i in range(1, 6):
    product = product * i
Factorial of 5
1
0
2
1
3
2
4
3
5
4
i
i
1
product
1

The product starts at 1. Pass one multiplies it by 1, so it stays 1.

Move 1 of 5

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.

Start a total at 0. Start a product at 1.
Quick check

A running product starts at 0 and the loop multiplies it by each number from 1 to 5. What is the final answer?

  1. A0
  2. B120
  3. C15
Show the answer

0. Zero times anything is zero, so the product never gets off the ground.

Your problem

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.

Example
n = 5 → 120

0 ≤ n ≤ 18

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding