Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
內容目錄
根據定義,尾隨零是「在一個數的最低有效位右邊的若干個零」。譬如 10 有 1 個尾隨零、13200 有 2 個尾隨零。
給定一個函式 zeros(n),求出 n 階乘 (n!) 後的尾隨零數量,譬如 zeros(5) 會回傳 1 (1*2*3*4*5 = 120,1 個尾隨零)。
從維基百科上,得到求任意數尾隨零的公式:
/**
* The calculation of trailing zero is based on the
* reference: https://en.wikipedia.org/wiki/Trailing_zero
*/
function zeros (n) {
let result = 0;
for ( var i = 1; Math.pow( 5, i ) <= n; i++ ){
result += Math.floor( n/Math.pow( 5, i ) );
}
return result;
}function zeros (n) {
var zs = 0;
while( n > 0 ){
n = Math.floor( n/5 );
zs += n;
}
return zs;
}投票評選的方法只使用了一個數學函式 Math.floor()。
這種作法其實是將上述的尾隨零公式再進一步拆解,第一次的 n = Math.floor( n/5 ) 是原本公式中 i = 1 的情況。藉由 n = Math.floor( n/5 ),可以讓第二次執行時,相當於 Math.floor( n/Math.pow( 5, 2 ) ),並將運算結果加總回 zs 中。
透過遞迴的方式,只需要重複使用 Math.floor() 即可,不需要另外呼叫 Math.pow()。