mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Update 172. Factorial Trailing Zeroes.md
This commit is contained in:
parent
e3873d8e74
commit
e4fe1bc795
@ -5,13 +5,14 @@
|
||||
(因为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,停止循环。
|
||||
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++
|
||||
@ -19,11 +20,14 @@ n = 4617.
|
||||
class Solution {
|
||||
public:
|
||||
int trailingZeroes(int n) {
|
||||
int result = 0;
|
||||
for(long long i=5; n / i > 0; i *= 5){
|
||||
result += (n/i);
|
||||
int res = 0, k = 5;
|
||||
|
||||
while(n >= k){
|
||||
res += n / k;
|
||||
if(k > INT_MAX / 5) break; //avoid overflow
|
||||
k *= 5;
|
||||
}
|
||||
return result;
|
||||
return res;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user