程序员面试金典——17.3阶乘尾零
Solution1:我的答案。没有更笨的方法了。。。
class Factor {
public:
int getFactorSuffixZero(int n) {
// write code here
int nums_2 = 0, nums_5 = 0;
for(int i = 1; i <= n; i++) {
nums_2 += nums_of_2(i);
nums_5 += nums_of_5(i);
}
return min(nums_2, nums_5);
}
int nums_of_2(int n) {
int res = 0;
while(n%2 == 0) {
res++;
n /= 2;
}
return res;
}
int nums_of_5(int n) {
int res = 0;
while(n%5 == 0) {
res++;
n /= 5;
}
return res;
}
};
Solution2:
参考网址:https://www.nowcoder.com/profile/9993586/codeBookDetail?submissionId=14652823
考虑进了概率的因素,大大降低了复杂度,好啊~~~
/*
* 思路:刚开始做这道题的时候,我是先求出n!再计算有多少个0
* 这样的复杂度很大,编译不通过,后来在编程之美中看到了思路,思路如下
* n!可以质因数分解,由于2*5=10,所以尾零的个数只与2和5有关
* 但是能被2整除的频率比被5整除的数高的多,所以尾零的个数其实只和5相关,
* n!能被多少个5解,就有多少个0,
* 这事,通过遍历(1到n)只要将能被5整除,就统计+1,最后统计的数,就是尾零的个数
*
*/
public class Factor {
public int getFactorSuffixZero(int n) {
int count=0;
for (int i = 1; i <=n; i++) {
int j = i;
while(j%5==0){
count++;
j/=5;
}
}
return count;
}
}