LeetCode/solutions/172. Factorial Trailing Zeroes.md
2020-07-01 21:27:25 +08:00

34 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [172. Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/description/)
# 思路
求某个数的阶乘有多少个0.
我们知道要想产生10只能是因子2与5相乘。要想产生因子2比较简单只要是偶数就行而产生因子5只能是5的倍数例如5、10、15、20...由此可知我们不用考虑怎么产生2
因为2实在是太多了每个一个数就有一个而5则需要每隔4个数才有一个
所以题目转换成1-n这n个数因式分解后有多少个5。很明显5的倍数至少有一个5的因子但是我们需要注意到25、50等等其实是蕴含了两个5的因子125、250等蕴含了三个5的因子...
例子:
n = 4617:
* 5^1 : 4617 ÷ 5 = 923.4, 所以一共得到923个因子5
* 5^2 : 4617 ÷ 25 = 184.68, 所以又得到额外的184个因子5
* 5^3 : 4617 ÷ 125 = 36.936, 所以又得到额外的36个因子5
* 5^4 : 4617 ÷ 625 = 7.3872, 所以又得到额外的7个因子5
* 5^5 : 4617 ÷ 3125 = 1.47744, 所以又得到额外的1个因子5
* 5^6 : 4617 ÷ 15625 = 0.295488, 结果小于1停止循环。
所以 4617! 有 923 + 184 + 36 + 7 + 1 = 1151 个尾0.
[参考](https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52373/Simple-CC++-Solution-(with-detailed-explaination))
# C++
``` C++
class Solution {
public:
int trailingZeroes(int n) {
int res = 0, k = 5;
while(n >= k){
res += n / k;
if(k > INT_MAX / 5) break; //avoid overflow
k *= 5;
}
return res;
}
};
```