Python程序:查找末尾有n个0的数字m


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

因此,如果输入为n = 2,则输出将为10,因为10!= 3628800,而9!= 362880,具有2个零的最小数字是10。

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个函数count_fives()。它将接收n作为输入。
  • cnt := 0
  • 当n > 0时,执行以下操作:
    • n := floor(n / 5)
    • cnt := cnt + n
  • 返回cnt
  • 在主方法中,执行以下操作:
  • left := 1
  • right := 5^24
  • 当right - left > 5时,执行以下操作:
    • mid := floor((right + left) / 10) * 5
    • fives := count_fives(mid)
    • 如果fives等于n,则:
      • right := mid
      • left := right - 5
      • 退出循环
    • 否则,如果fives < n,则:
      • left := mid
    • 否则:
      • right := mid
  • 返回right

示例

让我们看看以下实现以更好地理解:

Open Compiler
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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

10

更新于: 2021年10月25日

94 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告