描述
設計一個算法,計算出n階乘中尾部零的個數
要求
O(logN)的時間複雜度
思路:
n!中尾部零的個數,即有多少個10相乘 ≡ 2*5 。
而2的指數增長速度比5的指數增長速度要快,故2的個數比5多,隻需要考慮5的個數 tmp=n//5 個,
但是考慮到這 tmp = n//5 個數中,又有5的倍數,還能得到10。故繼續重複上一步的操作:tmp = tmp//5
以下圖為例,來源:https://blog.csdn.net/nwsuaf_uestc/article/details/78788932
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxyMjR0Tz0kaOVTS6hVMSdVYopkMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLzkzNyQTNxATMwIDMxkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
class Solution:
"""
@param: n: An integer
@return: An integer, denote the number of trailing zeros in n!
"""
def trailingZeros(self, n):
# write your code here, try to do it without arithmetic operators.
count = 0
tmp = n//5
while tmp != 0 :
count = count + tmp
tmp = tmp//5
return count