Factorial Trailing Zeroes

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 中记录的即为所求。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章