lintcode:Trailing Zeros

15:00 Start Write an algorithm which computes the number of trailing
zeros in n factorial.

Example 11! = 39916800, so the out should be 2

Challenge O(log N) time

阶乘末尾一个零表示一个进位,则相当于乘以10
而10 是由2*5所得,在1~100当中,可以产生10的有:0 2 4 5 6 8 结尾的数字,
显然2是足够的,因为4、6、8当中都含有因子2,所以都可看当是2,那么关键在于5的数量了
那么该问题的实质是要求出1~100含有多少个5
由特殊推广到一般的论证过程可得:
1、 每隔5个,会产生一个0,比如 5, 10 ,15,20.。。

2 、每隔 5×5 个会多产生出一个0,比如 25,50,75,100

3 、每隔 5×5×5 会多出一个0,比如125.

接着,请问N!的末尾有多少个零呢??

其实 也是同理的

N/5+N/25+……

class Solution {
 public:
    // param n : description of n
    // return: description of return 
    long long trailingZeros(long long n) {
        long long sum=0;
        while(n){
            sum+=n/5;
            n=n/5;
        }
        return sum;
    }
};

你可能感兴趣的:(lintcode)