Factorial Trailing Zeroes

题目: 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

解题思路: 根据数论里面的知识,任何正整数都可以表示为它的质因数的乘积wikipedia。所以比较准确的思路应该是计算质因数5和2的个数,取小的即可。质因数2的个数显然要大于5的个数,故只需要计算给定阶乘数中质因数中5的个数即可。原题的问题即转化为求阶乘数中质因数5的个数。

public int trailingZeroes(int n) {
    if (n < 0) {
        return -1;
    }

    int count = 0;
    for (; n > 0; n /= 5) {
        count += (n / 5);
    }

    return count;
}

results matching ""

    No results matching ""