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]

where k must be chosen such that

and  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

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;
}

 

你可能感兴趣的:(trailing,zeroes)