【Codewars python 5kyu】: Number of trailing zeros of N!

问题描述:

Write a program that will calculate the number of trailing zeros in a factorial of a given number.

N! = 1 * 2 * 3 * ... * N

Be careful 1000! has 2568 digits...

For more info, see: http://mathworld.wolfram.com/Factorial.html

Examples

zeros(6) = 1
# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero

zeros(12) = 2
# 12! = 479001600 --> 2 trailing zeros

Hint: You're not meant to calculate the factorial. Find another way to find the number of zeros.

代码实现:

#codewars第十三题
def zeros (n):
    num = 0
    while n > 4:
        n = math.floor(n/5)  
        num += n
    return num;
                             #计算结尾0的个数  主要是靠2*5产生0  但是2的话远多于5的个数 
                             #因为4*5  6*5  8*5  产生0 都可以转化为2*5  其中4 6 8 可以产生多个2
                             #计算5的个数:
                             #  5! = 5*4*3*2*1   1个5
                             #  10! =  10*9*...*5*4*...*1   2个五
                             #  16! =  16*15*...*10*9*...*5*4*...*1  3个五
                             #  36!  =  36*35*...*30*...*25*...*20*...*15*...10*...*5*...*1   8个五
                             # 最后发现求5的个数可以用 n//5  (大于4循环向下取整)   即可得5的个数

#另解
def zeros(n):
    x = n//5
    return x+zeros(x) if x else 0

zeros(1000)

 

你可能感兴趣的:(Codewars)