Skip to content
Problem 172 · LeetCode 172(opens in a new tab)

Factorial Trailing Zeroes

MediumMath

You are given a whole number n. Its factorial, n!, is the product 1 × 2 × 3 × ... × n, and 0! is 1.

Return how many zeros n! ends with when written in decimal. n! grows far too fast to compute directly, so you need to count the zeros without building it.

Example 1

Input:  n = 7
Output: 1
Why:    7! = 5040, one zero at the end
2 more examples and the constraints

Example 2

Input:  n = 30
Output: 7
Why:    6 multiples of 5, and 25 adds one more five

Example 3

Input:  n = 4
Output: 0
Why:    4! = 24 has no factor of 5

Constraints

  • 0 ≤ n ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count fives in each multipleO(n)
  2. Divide by powers of 5O(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 10,000Verdict
Count fives in each multipleO(n)
Passes; misses the follow-up
Divide by powers of 5O(log n)
Best; five rounds at most

n = the input number.

Edge cases to test

  • n = 0. 0! is 1, which has no zeros: return 0.
  • Below 5. 1! to 4! end in no zero; the loop never runs.
  • Powers of 5. 25 gives 6, not 5: 25 itself holds two fives.
  • The limit. n = 10,000 gives 2,000 + 400 + 80 + 16 + 3 = 2,499.

Common mistakes

  • Computing n! and counting zeros: it overflows long before n = 25 without big numbers.
  • Counting only n/5 and forgetting that 25, 50, 125, ... hold more than one five.
  • Building powers of 5 in a variable that can overflow; dividing n avoids that.

How to talk through it

  1. 1Clarify. Zeros at the end only, not inside? What is the largest n?
  2. 2Explain where zeros come from. Each one is 2 × 5, and there are always more twos, so count fives.
  3. 3Give the linear count. Count the fives in each multiple of 5: O(n).
  4. 4Count by layers. n/5 numbers give a first five, n/25 a second, and so on. Divide n by 5 until it is below 5.
  5. 5Test out loud. Run 0, 4, 25 and 30 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?