Number of trailing zeros of N!
Description:
Write a program that will calculate the number of trailing zeros in a factorial of a given number.
N! = 1 * 2 * 3 * 4 ... N
zeros(12) = 2 # 1 * 2 * 3 .. 12 = 479001600
that has 2 trailing zeros 4790016(00)
zeros(12) = 2 # 1 * 2 * 3 .. 12 = 479001600
that has 2 trailing zeros 4790016(00)
Be careful 1000! has length of 2568 digital numbers.
来自Codewars上的一个比较初级的题目,但是感觉还是挺有意思的就决定记录下来。
有趣的是最开始由于没有看到最下面的注意事项采用了比较暴力的方法来破解,很快发现这是个错误的方向,因为数字甚至很快就能超过Long的取值范围,改变一下思路发现想要末位是0的话就一定是需要2*5的。由于在公因子中2显然比5更多,所以只要知道5的个数就能够得到末位的0的个数。
其实就是将乘积做因式分解,只是不是对乘积本身而是对每一个乘数。
for (int i = 1; i <= n; i++) {
int j=i;
//因式分解
while (j%5==0){
result++;
j=j/5;
}
}
另外再贴一个别人的解法,比上面的简洁许多。
public class Solution {
public static int zeros(int n) {
int res = 0;
for (int i = 5; i <= n; i *= 5) {
res += n / i;
}
return res;
}
}