LintCode #2. 尾部的零
[问题地址]:https://www.lintcode.com/problem/trailing-zeros/description
解法一:
class Solution:
"""
@param: n: An integer
@return: An integer, denote the number of trailing zeros in n!
"""
def trailingZeros(self, n):
sum = 0
while n != 0:
n //= 5
sum+= n
return sum
说明:11! = 39916800,因此应该返回 2
对于这个问题,我们的思路如下,首先要想得到尾部为0,那么一定是乘以5或者5的倍数,才会得到这样的结果。
我们可以这样想比如N。= 1 * 2 * 3 * 4 * 5 * 6 * 7 * … * N-1 * N,把所有的乘数都因式分解,分解为质数相乘,则有如下式子:
N!= 1 * 2 * 3 * (2 * 2) * 5 * (2 * 3) * 7 * … ,那么可以看出,要使结果尾数有一个0,则需要乘数中有一对
2 * 5,很显然,在这些乘数中,2的个数比5的个数多得多,因此2*5的个数即为5的个数。那么,直接计算5的个数即可。
核心点:尾部的零有5的个数决定,单5(因式分解后有1个5)与某偶数相乘有单0,多5(因式分解后有多个5)与某偶数相乘有多个0。