#172

Factorial Trailing Zeroes

Medium
MathMathematical CountingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The number of trailing zeroes in n! is determined by the number of times 10 is a factor in the numbers from 1 to n. Since 10 is made from 2 and 5, and there are usually more factors of 2 than 5, we only need to count the factors of 5.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a count variable to 0.
  2. 2Step 2: While n is greater than or equal to 5, divide n by 5 and add the result to count.
  3. 3Step 3: Return the count.
solution.py7 lines
1# Full working Python code
2def trailing_zeroes(n):
3    count = 0
4    while n >= 5:
5        n //= 5
6        count += n
7    return count

Complexity note: The time complexity is O(log n) because we keep dividing n by 5 until it becomes less than 5, which reduces the problem size logarithmically.

  • 1The number of trailing zeroes is determined by the number of pairs of factors 2 and 5 in the factorial's prime factorization.
  • 2Since factors of 2 are more frequent than factors of 5, we only need to count the factors of 5.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.