0

I wrote a function to find the factorial and count the number of trailing zeros for the given input function. I wrote it in Javascript programming language. It gave me the correct answer till the input is 21, but after which it cannot calculate(Thinking I have reached my function upper bound). Can someone explain/give me optimized code to find trailing zeros till the input is 10,000 or more. Else is any other mathematical method to calculate? writing my code here.

function factorial(n) {
    var fact = 1;
    var value = "";
    var count = 0;
    for (var i = n; i > 1; i--) {
        value = value+(i+"*");
        fact = fact*i;
    }

    console.log(value + i + "=", fact);

    for (var i = n; i > 1; i--) {
        if (fact%10 === 0) {
            count++;
            fact = fact/10;
        }
    }

    console.log(count);
}
bmchaitu
  • 61
  • 1
  • 1
  • 7
  • The number of trailing zeros of n! is the floor(n/5) + floor(n/(5*5)) + floor(n/(5*5*5)) + ... – Paul Hankin Apr 19 '21 at 15:08
  • https://en.wikipedia.org/wiki/Trailing_zero#:~:text=The%20number%20of%20trailing%20zeros,small%20factors%20in%20integer%20factorization. – Paul Hankin Apr 19 '21 at 15:08

0 Answers0