mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 172. Factorial Trailing Zeroes.md
This commit is contained in:
parent
656ff744c0
commit
55826911f8
29
172. Factorial Trailing Zeroes.md
Normal file
29
172. Factorial Trailing Zeroes.md
Normal file
@ -0,0 +1,29 @@
|
||||
# [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++
|
||||
```
|
||||
class Solution {
|
||||
public:
|
||||
int trailingZeroes(int n) {
|
||||
int result = 0;
|
||||
for(long long i=5; n / i > 0; i *= 5){
|
||||
result += (n/i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user