JavaScript求阶乘的长度

计算大数阶乘的长度(数位),可以使用Stirling公式。

不过有两个特殊情况需要注意:

1. 0的阶乘长度,应该是1

2. 1的阶乘长度,也是1

这两点应该作判断。

function count(n) {
    
    if(n < 2){
        return 1;
    }

    var firstPart = 0.5 * Math.log(2 * Math.PI * n) / Math.log(10);
    var secondPart = n * Math.log(n / Math.E) / Math.log(10);
    var thirdPart = 1;
    
    return Math.floor(firstPart + secondPart + thirdPart);
}

猜你喜欢

转载自blog.csdn.net/esir82/article/details/79523565