Search code examples
rmathprecisionfloating-accuracy

how many trailing zeros after factorial?


I am trying to do this programming task:

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

I'm confused as one of the sample tests I have is showing this: expect_equal(zeros(30), 7)

I could be misunderstanding the task, but where do the trailing 7 zeros come from when the input is 30?

with scientific notation turned on I get this:

2.6525286e+32

and with it turned off I get this:

265252859812191032282026086406022

Solution

  • What you are experiencing is a result of this: Why are these numbers not equal?

    But in this case, calculating factorials to find the numbers of trailing zeros is not that efficient.

    We can count number of 5-factors in a number (since there will be always enough 2-factors to pair with them and create 10-factors). This function gives you trailing zeros for a factorial by counting 5-factors in a given number.

    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