1

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
Community
  • 1
  • 1
Steve
  • 625
  • 2
  • 5
  • 17
  • 2
    Hint: when calculating `6!`, which integers' product creates the zero? What about with `12!`? – Punintended Nov 18 '19 at 19:14
  • 1
    30! can't end with 22, because you've already seen that 6! ends with 0 -- there's no number you can multiply by 720 and NOT get a multiple of 10. So the result you got was clearly an error, probably due to floating decimal with Really Large Numbers – iod Nov 18 '19 at 19:27
  • R (and most other programming languages) do not use infinite precision for numbers. At some point, when the numbers get large enough, they are simply rounded to a convenient value. Computers are surprisingly bad at math. You will either need to create your own data type, or use an existing larger integer library, or think about factoring these numbers to predict the number of zeros without actually doing the multiplication. It's unclear from the question which of these techniques the question expects you do. I assume this is a homework question? – MrFlick Nov 18 '19 at 20:26

1 Answers1

0

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
M--
  • 25,431
  • 8
  • 61
  • 93