思路
設計一個算法,計算出n階乘中尾部零的個數
樣例
11! = 39916800,因此應該返回 2
分析
x! = r (我們需要計算 r 這個數字尾部有多少個0 )
r = (尾部不爲0的因子) * (10的n次方)
這裏的n就是我們需要計算得到的
那麼 11! = 11 * 10 * 9 * 8 ... 我們需要計算的就是10、2、5的個數。由於 10 = 2 * 5
所以我們只需要計算有多少個2和5, 然後取較小的因子的個數的數量
因爲是階乘, 所以2的個數遠大於5的個數, 所以我們只需要計算因子5的個數
Python
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.
return self.func_2(n)
def func_1(self, n):
# 循環1~n, 暴力求其每個數字5的因子的數量的和
zeros = 0
if n == 0:
return 1
for i in range(1, n + 1):
number = i
while number and number % 5 == 0:
zeros += 1
number /= 5
return zeros
def func_2(self, n):
# 循環1~n, 求單一數字x的因子5的個數可以優化爲:
# zeros = [n / 5] + [n / 5*2] + ····
# 例如 26! = 1 × 2 ×3× 4 × 5 × 6 × 7 × 8 × 9 × 10 × 11 × 12 × 13× 14
# × 15 × 16 × 17 × 18 × 19 × 20 × 21 × 22 ×23× 24 × 25 × 26
# zeros = int(26 / 5) + int(26 / 25) = 6
# 25 = 5 * 5 被少計算一次,類推5的x次方被少計算x-1次
zeros = 0
if n == 0:
return 1
i = 5
while i <= n:
zeros += int(n / i)
i *= 5
return zeros
if __name__ == '__main__':
s = Solution()
print(s.trailingZeros(5))
print(s.trailingZeros(11))
print(s.trailingZeros(105))
print(s.trailingZeros(125))
print(s.trailingZeros(30000))
print(s.trailingZeros(1001171717))
Go
package main
import "fmt"
/**
* @param n: A long integer
* @return: An integer, denote the number of trailing zeros in n!
*/
func trailingZeros(n int64) int64 {
// write your code here, try to do it without arithmetic operators.
var zeros, i int64
for i = 5; ; i *= 5 {
zeros += n / i
if n/i == 0 {
break
}
}
return zeros
}
func main() {
fmt.Println(trailingZeros(11))
}