Program to count number of trailing zeros of minimum number x which is divisible by all values from 1 to k in Python

When we need to find the smallest positive integer x that is divisible by all numbers from 1 to k, we're looking for the Least Common Multiple (LCM) of numbers 1 through k. The trailing zeros in this LCM depend on how many times 10 divides it, which is determined by the minimum of powers of 2 and 5 in the prime factorization.

For example, if k = 6, the LCM of {1, 2, 3, 4, 5, 6} is 60. The number 60 has one trailing zero because it contains one factor of 10 (2 × 5).

Algorithm

Since powers of 2 are always more abundant than powers of 5 in factorials, the number of trailing zeros equals the number of times 5 divides the LCM. We count powers of 5: 5¹, 5², 5³, etc., up to k.

Implementation

class Solution:
    def solve(self, k):
        res = 0
        x = 1
        while x * 5 <= k:
            res += 1
            x *= 5
        return res

# Test the solution
ob = Solution()
k = 6
result = ob.solve(k)
print(f"For k = {k}, trailing zeros: {result}")

# Test with more examples
test_cases = [5, 10, 25, 100]
for k in test_cases:
    zeros = ob.solve(k)
    print(f"k = {k}: {zeros} trailing zeros")
For k = 6, trailing zeros: 1
k = 5: 1 trailing zeros
k = 10: 2 trailing zeros
k = 25: 6 trailing zeros
k = 100: 24 trailing zeros

How It Works

The algorithm counts how many powers of 5 are ? k:

  • 5¹ = 5: contributes 1 factor of 5

  • 5² = 25: contributes 1 additional factor of 5

  • 5³ = 125: contributes 1 additional factor of 5

For k = 25, we have 5¹ and 5² ? 25, but multiples like 25 contribute extra factors, giving us more trailing zeros than just counting multiples of 5.

Alternative Implementation

def count_trailing_zeros(k):
    """Count trailing zeros in LCM of numbers 1 to k"""
    count = 0
    power_of_5 = 5
    
    while power_of_5 <= k:
        count += 1
        power_of_5 *= 5
    
    return count

# Test with examples
examples = [6, 10, 25, 100, 125]
for k in examples:
    zeros = count_trailing_zeros(k)
    print(f"k = {k}: {zeros} trailing zeros")
k = 6: 1 trailing zeros
k = 10: 2 trailing zeros
k = 25: 6 trailing zeros
k = 100: 24 trailing zeros
k = 125: 31 trailing zeros

Conclusion

To count trailing zeros in the LCM of numbers 1 to k, we count how many powers of 5 are less than or equal to k. This works because trailing zeros come from factors of 10, and there are always more factors of 2 than 5 in the LCM.

Updated on: 2026-03-25T13:58:13+05:30

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements