leetcode[172]Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

给定一个整数n,返回n!(n的阶乘)数字中的后缀0的个数。

n!的后缀0总是由质因子2和质因子5相乘得来的。2的个数大于等于5的个数,计算出5的个数问题就解决了。

n!后缀0的个数 = n!质因子中5的个数 = floor(n/5) + floor(n/25) + floor(n/125) + ....

class Solution {
public:
/**
n!后缀0的个数 = n!质因子中5的个数
              = floor(n/5) + floor(n/25) + floor(n/125) + ....
*/
    int trailingZeroes(int n) {
       int res=0;
       while(n/5)
       {
           n/=5;
           res+=n;
       }
       return res;
    }
};

 

posted @ 2015-02-08 23:22  Vae永Silence  阅读(130)  评论(0编辑  收藏  举报