Easy-题目32:172. Factorial Trailing Zeroes

来源:互联网 发布:浙江理工大学知乎 编辑:程序博客网 时间:2024/06/03 11:44

题目原文:
Given an integer n, return the number of trailing zeroes in n!.
题目大意:
给出正整数n,求n!末尾有几个0.
题目分析:
trivial的做法是把n!求出来,然后除10直到余数不为0,但开销太大(使用BigInteger)
那么分析一下:
(1)0的来源是2*5=10,那么将n!因式分解,有几个2*5就有几个0;
(2)只有末尾是5和0的数里面才有因子5,所以无论如何,n!中因子5都比因子2多,因此数n!里面有几个因子5即可。
(3)接下来比较难以理解,使用分治算法逐步降低问题规模,其递推公式为:
令f(x)表示正整数x中因子5的个数
当0 < n < 5时,f(n!) = 0;
当n >= 5时,f(n!) = k + f(k!), 其中 k = n / 5(取整)。
源码:(language:c)

int trailingZeroes(int n) {    int ret = 0;    while(n) {        ret += n/5;        n /= 5;    }    return ret;  }

成绩:
0ms,beats 62.92%,众数4ms,59.55%.
cmershen的碎碎念::
代码实现仅有6行,但其中的数学背景却不是很好理解。该递推关系的数学推导见http://blog.csdn.net/niushuai666/article/details/6695790

0 0