在 Python 中查找数字 m 使其末尾有 n 个 0 的程序

假设我们有一个数字 n。我们必须找到最小的数 m,使得 m 的阶乘至少有 n 个 0。

因此,如果输入类似于 n = 2,那么输出将是 10,因为 10!= 3628800 和 9!= 362880,带 2 个零的最小数字是 10。

示例

让我们看看以下实现以获得更好的理解 -

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))

输入

2
输出结果
10

猜你喜欢