codewars--js--Number of trailing zeros of N!

问题描述:

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

Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.

刚刚开始做的时候,很直接的思路就是先求阶乘,然后求尾部0的个数。后来发现,当数据超过一定位数时,js会以科学计数法表示,不能直接计算0的个数。

接着就是思考有2*5能出来0,然后5的个数相对于2的个数会比较少,所以就求5作为因子出现了多少次。

我的答案:

function zeros (n) {
var num=0;
  for(var i=1;i<=n;i++){
    var j=i;
    while(j%5==0){
      num=num+1;
      j=j/5;
    }
  }
  return num;
}

优秀答案:

1 function zeros (n) {
2   var zs = 0;
3   while(n>0){
4     n=Math.floor(n/5);
5     zs+=n
6   }
7   return zs;
8 }
原文地址:https://www.cnblogs.com/hiluna/p/8854675.html