本题难在数学分析,要进行数学分析后,才能得出相应的结论,再根据结论来写代码。

在数学中,阶乘的尾部零是由因子 2 和 5 相乘得到的,而在阶乘中,因子 2 的数量远多于因子 5,因此只需计算阶乘中包含多少个 5 的因子即可。

实现步骤

  1. 初始化计数器 创建一个变量 count 用于记录 5 的因子总数。
  2. 循环计算因子 5 的个数 不断将 n 除以 5,并将结果累加到 count 中。 对于 25、125 等 5 的幂次,还需多加一次,因为它们包含多个 5 因子。
  3. 返回结果 循环结束后,count 即为尾部零的个数。

验证方法

数学公式:尾零个数 = ⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ +...

与直接计算 math.factorial(50) 再统计末尾零的方法对比,结果一致,但本算法时间复杂度为 O(log n),效率更高。

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# the number of 0
# @param n long长整型 the number
# @return long长整型
#
class Solution:
    def thenumberof0(self , n: int) -> int:
        # write code here
        count = 0
        while n>=5:
            n //= 5
            count += n
        return count