首页 > 解决方案 > 阶乘后有多少个尾随零?

问题描述

我正在尝试执行此编程任务:

编写一个程序,计算给定数字的阶乘中尾随零的数量。

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

小心1000!有 2568 位数字。

有关详细信息,请参阅: http: //mathworld.wolfram.com/Factorial.html

例子:

零(6)= 1 -> 6!= 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 个尾随零

零(12)= 2 -> 12!= 479001600 --> 2 个尾随零

我很困惑,因为我的示例测试之一显示了这一点:expect_equal(zeros(30), 7)

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

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

2.6525286e+32

并关闭它,我得到这个:

265252859812191032282026086406022

标签: rmathprecisionfloating-accuracy

解决方案


您正在经历的结果是:为什么这些数字不相等?

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

我们可以计算一个数字中5 因子的数量(因为总会有足够的 2 因子与它们配对并创建 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

推荐阅读