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 smallest number m, such that factorial of m has at least n number of 0s.

So, if the input is like n = 2, then the output will be 10 because 10! = 3628800 and 9! = 362880, minimum number with 2 zeros is 10.

To solve this, we will follow these steps −

  • Define a function count_fives() . This will take n
  • cnt := 0
  • while n > 0, do
    • n := floor of (n / 5)
    • cnt := cnt + n
  • return cnt
  • From the main method, do the following −
  • left := 1
  • right := 5^24
  • while right - left > 5, do
    • mid := floor of ((right + left) / 10) * 5
    • fives := count_fives(mid)
    • if fives is same as n, then
      • right := mid
      • left := right - 5
      • come out from the loop
    • otherwise when fives < n, then
      • left := mid
    • otherwise,
      • right := mid
  • return right

Example

Let us see the following implementation to get better understanding −

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

def solve(n):
   left = 1
   right = 5**24
   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

n = 2
print(solve(n))

Input

2

Output

10

Updated on: 25-Oct-2021

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements