LintCode——尾部的零

尾部的零:设计一个算法,计算出n阶乘中尾部零的个数

样例:11! = 39916800、因此应该返回2

分析:假如你把1 × 2 ×3× 4 ×……×N中每一个因数分解质因数,例如 1 × 2 × 3 × (2 × 2) × 5 × (2 × 3) × 7 × (2 × 2 ×2) ×……

   10进制数结尾的每一个0都表示有一个因数10存在。

           10可以分解为2 × 5,因此只有质数2和5相乘能产生0,别的任何两个质数相乘都不能产生0,而且2,5相乘只产生一个0。 所以,分解后的整个因数式中有多少对(2,5),

结果中就有多少个0,而分解的结果中,2的个数显然是多于5的,因此,有多少个5,就有多少个(2, 5)对。 所以,讨论n的阶乘结尾有几个0的问题,就被转换成了1到n所有这些

数的质因数分解式有多少个5的问题。

1、Python

 1 class Solution:
 2     """
 3     @param: n: An integer
 4     @return: An integer, denote the number of trailing zeros in n!
 5     """
 6     def trailingZeros(self, n):
 7         # write your code here, try to do it without arithmetic operators.
 8         sum = 0
 9         while n > 0:
10             sum += n // 5
11             n //= 5
12         return sum

 2、Java

 1 public class Solution {
 2     /*
 3      * @param n: An integer
 4      * @return: An integer, denote the number of trailing zeros in n!
 5      */
 6     public long trailingZeros(long n) {
 7         // write your code here, try to do it without arithmetic operators.
 8         int sum = 0;
 9         while(n>0){
10             sum+=n/5;
11             n/=5;
12         }
13         return sum;
14     }
15 }

猜你喜欢

转载自www.cnblogs.com/wangcj2015/p/9050031.html