Program to find number m such that it has n number of 0s at end in Python

Suppose we have a number n. We have to find the smallest number m, such that factorial of m has at least n number of trailing zeros.

So, if the input is like n = 2, then the output will be 10 because 10! = 3628800 has 2 trailing zeros and 9! = 362880 has only 1 trailing zero, so the minimum number with at least 2 zeros is 10.

Understanding the Problem

Trailing zeros in a factorial are created by factors of 10, which come from pairs of factors 2 and 5. Since there are always more factors of 2 than 5 in any factorial, we only need to count the factors of 5.

Counting Factors of 5

The number of factors of 5 in n! is calculated using Legendre's formula ?

def count_fives(n):
    cnt = 0
    while n > 0:
        n = n // 5
        cnt += n
    return cnt

# Test the function
print("Factors of 5 in 10!:", count_fives(10))
print("Factors of 5 in 15!:", count_fives(15))
Factors of 5 in 10!: 2
Factors of 5 in 15!: 3

Binary Search Solution

Since the number of trailing zeros increases monotonically with factorial values, we can use binary search to find the smallest m ?

def count_fives(n):
    cnt = 0
    while n > 0:
        n = n // 5
        cnt += n
    return cnt

def solve(n):
    left = 1
    right = 5**24  # Large upper bound
    
    while right - left > 5:
        mid = int((right + left) / 10) * 5
        fives = count_fives(mid)
        
        if fives == n:
            right = mid
            left = right - 5
            break
        elif fives < n:
            left = mid
        else:
            right = mid
    
    return right

# Test cases
test_cases = [2, 5, 10]
for n in test_cases:
    result = solve(n)
    print(f"n = {n}: smallest m = {result}, trailing zeros in {result}! = {count_fives(result)}")
n = 2: smallest m = 10, trailing zeros in 10! = 2
n = 5: smallest m = 25, trailing zeros in 25! = 6
n = 10: smallest m = 45, trailing zeros in 45! = 10

How It Works

The algorithm works in two steps:

  1. Count factors of 5: For any number m, count how many factors of 5 exist in m! using Legendre's formula
  2. Binary search: Find the smallest m where the count of factors of 5 is at least n

The binary search optimization ensures we check multiples of 5 only, since trailing zeros can only increase at multiples of 5.

Conclusion

This solution uses binary search combined with Legendre's formula to efficiently find the smallest factorial with at least n trailing zeros. The time complexity is O(log n × log m) where m is the result.

Updated on: 2026-03-26T18:28:54+05:30

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements