【编程题】阶乘后的零(Java实现)
题目来源
程序员面试经典
https://www.nowcoder.com/practice/434922f9f4724b97b83c417e884008f1?tpId=8&tqId=11058&tPage=4&rp=4&ru=/ta/cracking-the-coding-interview&qru=/ta/cracking-the-coding-interview/question-ranking
leetcode第172
https://leetcode-cn.com/problems/factorial-trailing-zeroes/comments/
题目描述
请设计一个算法,计算n的阶乘有多少个尾随零。
给定一个int n,请返回n的阶乘的尾零个数。保证n为正整数。
测试样例:
5
返回:1
解答
方法一 思路
1、找规律 6!=6 * 5 * 4 * 3 * 2 * 1=120=6*(5 * 2) * 4 * 3 * 1;有一个零
10!=10* 9* 8* 7* 6* 5* 4* 3* 2* 1=(5 * 2)* 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1=(5 * 2)* 9* 8* 7* 6* (5 * 2) * 4 * 3 * 1;有两个零。
2、分析:只有25末尾才有0,所以就可以抛去其他数据 专门看2和 5 以及其倍数 ,因为4 * 25末尾也是0;
比如10! = 2 * 4 * 5 * 6 * 8 * 10;
其中 4能拆成22 ,10能拆成2*5 ;
所以10! = 2 * ( 2 * 2 ) * 5 * (2 * 3) * (2 * 2 * 2) * (2 * 5)一个2和一个5配对就产生一个0
所以10!末尾2个0,又因为2的个数比5多,所以只要有一个5就可以找到一个2与他匹配,因此只需要计算5的个数就行了。
假若n=29
29里能凑10的5为5, 2 * 5, 3 * 5, 4 * 5, 25其中 25还能拆为 两个5相乘
所以,里面的5的个数为 int(29/5) + int(29/25),
3、当5^i>0时
f(n)=int(n/5)+int(n/25)…int(n/(5^i);
代码
import java.util.*;
public class Factor {
public int getFactorSuffixZero(int n) {
// write code here
int count=0;
for(int i = 1;;i++){
int number = n/(int)Math.pow(5,i);
if(number == 0)
break;
count+= number;
}
return count;
}
}
方法二 思路
将刚刚方法一是思路最后一步进行优化
count+=n/(int)(Math.pow(5,i)中等价于
count+=n/5/5/5/5……;
即计算循环值n/5的个数
代码如下
import java.util.*;
public class Factor {
public int getFactorSuffixZero(int n) {
// write code here
int count=0;
while(n>=5){
count+=n/5;
n=n/5;
}
return count;
}
}