设计一个算法,计算出n阶乘中尾部零的个数
样例
样例 1:
输入: 11
输出: 2
样例解释:
11! = 39916800, 结尾的0有2个。
样例 2:
输入: 5
输出: 1
样例解释:
5! = 120, 结尾的0有1个。
原理
假如你把1 × 2 ×3× 4 ×……×N中每一个因数分解质因数,结果就像:
1 × 2 × 3 × (2 × 2) × 5 × (2 × 3) × 7 × (2 × 2 ×2) ×……
10进制数结尾的每一个0都表示有一个因数10存在——任何进制都一样,对于一个M进制的数,让结尾多一个0就等价于乘以M。
10可以分解为2 × 5——因此只有质数2和5相乘能产生0,别的任何两个质数相乘都不能产生0,而且2,5相乘只产生一个0。
所以,分解后的整个因数式中有多少对(2, 5),结果中就有多少个0,而分解的结果中,2的个数显然是多于5的,因此,有多少个5,就有多少个(2, 5)对。
所以,讨论1000的阶乘结尾有几个0的问题,就被转换成了1到1000所有这些数的质因数分解式有多少个5的问题。
公式
求末尾0的个数:
至于一个数阶乘的末尾有多少个0,0的个数为(其中的“/”是取整除法):
例子:1000的阶乘末尾0的个数
1000/5^1 + 1000/5^2 + 1000/5^3 + 1000/5^4
= 200 + 40 + 8 + 1
= 249(个)
注:5^4 :五的四次方,因为5^4 小于1000,5^5大于1000,所以加到5^4
所以,具体的代码操作如下所示:
public class Solution {
/*
* @param n: An integer
* @return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
// write your code here, try to do it without arithmetic operators.
long count = 0;//定义零的个数初始化为0
for(int i=1;Math.pow(5,i)<=n;i++){
//Math.pow(5,i)函数,是计算5的i次方的值
count += n/(long)Math.pow(5,i);//计算出5的个数的总和
}
return count;
}
}
public class Solution {
/*
* @param n: An integer
* @return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
// write your code here, try to do it without arithmetic operators.
long count = 0;//定义零的个数初始化为0
while(n!=0){
count += n/5;//计算出5的个数的总和
n/=5;
}
return count;
}
}
/*假设n=1000,则对于while循环来说:
*第一次,count = 200 n = 200 5^1
*第二次,count = 200+40 n = 40 5^2
*第三次,count = 200+40+8 n = 8 5^3
*第四次,count = 200+40+8+1 n = 1 5^4
*第五次,count = 200+40+8+1+0 n = 0 5^5 > 1000 ,所以结果为0
*/