Press "Enter" to skip to content

花花酱 LeetCode 793. Preimage Size of Factorial Zeroes Function

Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * ... * x, and by convention, 0! = 1.)

For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.


  • K will be an integer in the range [0, 10^9].


First we need to compute how many trailing zeros n! has.

See  花花酱 LeetCode 172. Factorial Trailing Zeroes for details

It’s hard to say how many numbers have trailing zeros equals to K, but we can find the largest number p whose trailing zeros is K using binary search. (p+1)! has more than K trailing zeros. And do the same thing to find the largest number q whose trailing zeros is K – 1 using binary search.

Then we know that are exact p numbers 1,2,…,p whose trailing zeros are less or equal to K.

And exact q numbers 1, 2, …, q whose trailing zeros are less or equal to K – 1.

q + 1, q + 2, …, m (m – q numbers in total) the numbers with trailing zeros equal to K.

Solution 1: Math + Binary Search

Time complexity: O(log2(INT_MAX)*log5(INT_MAX))

Space complexity: O(1)



If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website


One Comment

  1. zhoyifan zhoyifan March 17, 2018

    官方solution对int l int r 的初始值范围限定更小。int l=K,int r=10*K+1.可是我没看懂它是怎么得出来的。。。

Leave a Reply