Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to
@ts for adding this problem and creating all test cases.
要求:計算 n! (n的階乘)的值末尾有幾個零
首先想到,偶數足夠多,找到末尾是5,10,50...的數並計數:
5,10 一個零
50,100 兩個零
500,1000 三個零
。。。。。
後來經驗證發現,像25這種會產生 兩個零,而根據上面的計算,只計算了 一個零
=========================
總結髮現,我們從本質出發,只需找到 n! 按照質數乘積的形式展開后里面有幾個 5 即可
例如:10! = 1×2×3×4×5×6×7×8×9×10 = 2×3×2×2×5×2×3×7×2×2×2×3×3×2×5 = 2^8 × 3^4 × 5^2 × 7^1
所以 10! 末尾有 兩個零(驗證一下 10! = 3628800,正確)
=========================
程序算法:
記錄 num / 5,加到 ans 裏,然後把 num 除以 5,直到 num == 0 爲止,ans 中記錄的即爲所求。