阶乘后有多少尾随零?

how many trailing zeros after factorial?

我正在尝试完成这个编程任务:

Write a program that will calculate the number of trailing zeros in a factorial of a given number.

N! = 1 * 2 * 3 * ... * N

Be careful 1000! has 2568 digits.

For more info, see: http://mathworld.wolfram.com/Factorial.html

Examples:

zeros(6) = 1 -> 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero

zeros(12) = 2 -> 12! = 479001600 --> 2 trailing zeros

我很困惑,因为我的一个样本测试显示了这个:expect_equal(zeros(30), 7)

我可能误解了这个任务,但是当输入为 30 时,尾随的 7 个零从何而来?

打开科学记数法我得到这个:

2.6525286e+32

关闭它后我得到这个:

265252859812191032282026086406022

您遇到的是以下结果:Why are these numbers not equal?

但在这种情况下,计算阶乘以找到尾随零的数量并不是那么有效。

我们可以计算一个数字中 5-factors 的数量(因为总会有足够的 2-factors 与它们配对并创建 10 个因素)。此函数通过计算给定数字中的 5 个因子,为您提供阶乘的尾随零。

tailingzeros_factorial <- function(N){

  mcount = 0L
  mdiv = 5L
  N = as.integer(N)

  while (as.integer((N/mdiv)) > 0L) {

    mcount = mcount +  as.integer(N/mdiv)
    mdiv = as.integer(mdiv * 5L)
  }
  return(mcount)
}
tailingzeros_factorial(6)
 #> 1

tailingzeros_factorial(25)
 #> 6

tailingzeros_factorial(30)
 #> 7