• 在Python 中計算階層(factorial)的方法: math.factorial, numpy.math.factorial, scipy.math.factorial

解法1 (被判定Codewars沒效率):


In [1]:
import numpy as np

def zeros(n):
    if n < 5:
        return 0
    else:
        f = np.math.factorial(n)
        i = 1
        while str(f // (10 ** i))[-1] == '0':
            i = i + 1    
        return i

print(zeros(12))
print(zeros(1000))


2
249

解法2 (被Codewars判定沒效率):


In [2]:
import numpy as np

def zeros(n):
    f = np.math.factorial(n)    
    i = 1
    while np.sum(np.array([n for n in str(f)], int)[-i:]) == 0:
        i = i + 1    
    return i-1

print(zeros(12))
print(zeros(1000))


2
249

解法3 (被Codewars判定沒效率):


In [3]:
import numpy as np

def zeros(n):
    f = np.math.factorial(n)
    #arry = np.array([n for n in str(f)], int)[::-1]
    arry = np.array(list(str(f)), int)[::-1]
    ind = np.nonzero(arry)[0]          
    return ind.min()

print(zeros(12))
print(zeros(1000))


2
249

解法4 (被Codewars判定沒效率):


In [4]:
def zeros(n):
    res = 0
    for i in range(n):
        res +=  (n // (5 ** (i+1)))
    return res

print(zeros(12))
print(zeros(1000))


2
249

解法5


In [5]:
def zeros(n):
    res = 0
    while(n):
        res += n // 5
        n = n // 5
    return res
    
print(zeros(12))
print(zeros(1000))


2
249

解法6