Trailing Zeros (Factorial)

Question: 

Write an algorithm which computes the number of trailing zeros in n factorial.

 
Example:

11! = 39916800, so the out should be 2

 
Analysis:
所有大于2的整数都可以表示成质数的乘积(X = 2^n0 * 3^n1 * 5^n2 * 7^n3 * 11^n4 ......)。所有的因子中,一个2和一个5配对起来,就会多一个“0”。因此我们计算(2,5)组合的个数就行。又因为2的个数往往比5多很多,所以计算5的个数就可以了。
最终得到一个公式:0的个数 = 因子5的个数 = n/5 + n/25 + n/125 + ...
 
Code:
 1 class Solution {
 2     /*
 3      * param n: As desciption
 4      * return: An integer, denote the number of trailing zeros in n!
 5      */
 6     public long trailingZeros(long n) {
 7         if(n < 0) {
 8             return -1; 
 9         }
10         
11         long count = 0;
12         for(long i = 5; n / i >= 1; i *= 5) {
13             count += n / i;
14         }
15         
16         return count;
17     }
18 };

 

 
Complexity:
时间复杂度是O(logn)。
 

参考:

http://www.danielbit.com/blog/puzzle/leetcode/leetcode-factorial-trailing-zeroes

posted on 2016-01-20 15:41  BillZ  阅读(169)  评论(0编辑  收藏  举报

导航