Problem 172

Abstract / Summary

Count the number of trailing zeros in the factorial of a given number by finding how many times it can be divided by ten.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0172.py

class Solution:
    def trailingZeroes(self, n: int) -> int:
        # count factors which are multiple of 5
        # (there are many more multiples of 2, no need to count them)
        result = 0
        for i in range(5, n+1, 5):
            n = i
            while n % 5 == 0:
                result += 1
                n //= 5

        return result
12 lines | 368 bytes | submitted August 15, 2023 | GitHub   22% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 47% (1+ million submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method trailingZeroes that computes the number of trailing zeroes in the factorial of a non-negative integer n. The algorithm focuses on counting the factors of 5 that appear in the product sequence from 1 to n, because each pair of a factor 2 and a factor 5 contributes a trailing zero, and factors of 2 are abundant relative to factors of 5.

Core Logic

The method begins by initializing an accumulator result to zero. This variable will hold the total count of factor 5 occurrences.

result = 0

A for loop iterates over every multiple of 5 up to and including n. The loop step size of 5 ensures that only numbers that can contribute at least one factor of 5 are examined, eliminating unnecessary checks on numbers that are not divisible by 5.

for i in range(5, n + 1, 5):

Inside the loop, the current multiple i is assigned back to the variable n. This temporary reassignment allows the inner while loop to repeatedly divide the current number by 5, extracting all powers of 5 present in that specific multiple.

    n = i

The while loop continues as long as the temporary n remains divisible by 5. Each successful division indicates another factor of 5, so the accumulator result is incremented, and n is reduced by integer division with 5. This process captures numbers such as 25 (which contributes two factors of 5) and 125 (which contributes three factors of 5) in a single iteration.

    while n % 5 == 0:
        result += 1
        n //= 5

After the loop finishes processing all multiples of 5, the method returns the accumulated count, which equals the number of trailing zeroes in n!.

return result

Edge Cases

When n is less than 5, the range in the for loop produces no iterations, leaving result at its initial value of zero. This correctly reflects that factorials of numbers 0 through 4 have no trailing zeroes.

For values of n that are exact powers of 5, such as 5, 25, 125, etc., the inner while loop extracts multiple factors from a single iteration, ensuring that higher powers of 5 are fully accounted for without requiring separate passes.

When n is a very large integer, the loop still processes only the multiples of 5, and the inner division reduces each examined number quickly, preventing excessive work on numbers that contain many factors of 5.

Performance Considerations

The algorithm reduces the number of iterations by stepping through the range with an increment of 5, thereby skipping all numbers that cannot contribute a factor of 5. This selective iteration cuts down the total loop count roughly to one fifth of the naïve approach that would examine every integer up to n.

Within each iteration, the inner while loop divides the current multiple by 5 until it is no longer divisible. Because each division reduces the value exponentially, the number of inner loop executions for any given multiple is bounded by the logarithm of that multiple base 5. Consequently, the overall work performed scales with the total number of factor 5 occurrences rather than with the magnitude of n itself.

The reuse of the variable n as a temporary holder for each multiple avoids the allocation of additional storage, keeping the memory footprint minimal throughout execution. The method relies solely on integer arithmetic, which is efficient on typical hardware.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a giant pile of blocks, and you want to know how many zeros are hiding at the end of a big number. To find these zeros, you look for pairs of two and five because when those two numbers hug each other, they create a ten, and tens always end in a zero. Since there are always plenty of twos in the world, the goal is just to count how many times the number five can hide inside the numbers up to your big number.

The code starts with a count of zero. Then, it goes through every number that can be divided by five. For each of those numbers, it checks to see how many fives are tucked away inside. If a number is twenty-five, it actually has two fives hidden inside, so the code counts both of them. It keeps doing this for every multiple of five until it finishes checking all the numbers. Every time it finds a five, it adds one to the final count.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.30 | σ = 1.74

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
zfang399 C++
45 links | 31 authors | 10 languages

Videos

12 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality