LeetCode 0172 Factorial Trailing Zeroes
作者:互联网
1. 题目描述
2. Solution 1
1、思路分析
区间[1, n]中质因子p的倍数有\(n_1 = \lfloor \frac{n}{p} \rfloor\)个,这些数至少贡献了\(n_1\)个质因子。\(p^2\)的倍数有\(n_2=\lfloor \frac{n}{p^2} \rfloor\)个,由于这些数已经是\(p\)的倍数了,为了不重复统计\(p\)的个数,仅考虑额外贡献的质因子个数,即这些数额外贡献了至少\(n_2\)个质因子\(p\)。以此类推,[1, n]中质因子\(p\)的个数为 \(\sum_{k=1}^{ \infty}\lfloor \frac{n}{p^k} \rfloor\)
上式表明:
1> n不变,p越大,质因子个数越少,因此[1, n]中质因子5的个数不会大于质因子2的个数;
2> [1, n]中质因子5的个数为: \(\sum_{k=1}^{\infty} \lfloor \frac{n}{5^k} \rfloor < \sum_{k=1}^{\infty} \frac{n}{5^k} = \frac{n}{4} = O(n)\)
代码实现时,由于 \(\lfloor \frac{n}{5^k} \rfloor = \lfloor \frac{\lfloor \frac{n}{5^{k-1}} \rfloor }{5} \rfloor\)
因此,可以通过不断将n除以5,并累加每次除后的n,来得到答案。
2、代码实现
package Q0199.Q0172FactorialTrailingZeroes;
/*
Iteration
*/
public class Solution2 {
public int trailingZeroes(int n) {
int res= 0;
while (n >= 5) {
n = n / 5;
res += n;
}
return res;
}
}
3、复杂度分析
时间复杂度: O(log n)
空间复杂度: O(1)
3. Solution 2
1、思路分析
Solution1的递归实现。
2、代码实现
package Q0199.Q0172FactorialTrailingZeroes;
/*
Because all trailing 0 is from factors 5 * 2.
But sometimes one number may have several 5 factors, for example, 25 have two 5 factors, 125 have tree 5 factors.
In the n! operation, factors 2 is always ample. So we just count how many 5 factors in all number from 1 to n.
*/
public class Solution {
// recursion
public int trailingZeroes(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
}
}
3、复杂度分析
时间复杂度: O(log n)
空间复杂度: O(log n)
标签:Zeroes,lfloor,frac,factors,Factorial,0172,rfloor,因子,复杂度 来源: https://www.cnblogs.com/junstat/p/16323595.html