`

请您先登录,才能继续操作

LeetCode - Factorial Trailing Zeroes

阅读更多

 

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

Note: Your solution should be in logarithmic time complexity.

这个要用到数学知识了。参见Wikipedia-Trailing Zeroes

The number of trailing zeros in the decimal representation of n!, the factorial of a non-negative integer n, is simply the multiplicity of the primefactor 5 in n!. This can be determined with this special case of de Polignac's formula:[1]

f(n) = \sum_{i=1}^k \left \lfloor \frac{n}{5^i} \right \rfloor =
\left \lfloor \frac{n}{5} \right \rfloor + \left \lfloor \frac{n}{5^2} \right \rfloor + \left \lfloor \frac{n}{5^3} \right \rfloor + \cdots + \left \lfloor \frac{n}{5^k} \right \rfloor, \,

where k must be chosen such that

5^{k+1} > n,\,

and \lfloor a \rfloor denotes the floor function applied to a. For n = 0, 1, 2, ... this is

0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 6, ... (sequence A027868 in OEIS).

For example, 53 > 32, and therefore 32! = 263130836933693530167218012160000000 ends in

\left \lfloor \frac{32}{5} \right \rfloor + \left \lfloor \frac{32}{5^2} \right \rfloor = 6 + 1 = 7\,

zeros. If n < 5, the inequality is satisfied by k = 0; in that case the sum is empty, giving the answer 0.

Solution:

public int trailingZeroes(int n) {
    int count = 0;
    while(n>=5) {
        n /= 5;
        count += n;
    }
    return count;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics