website/content.en/ChapterFour/0700~0799/0793.Preimage-Size-of-Factorial-Zeroes-Function.md
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.
Example 1:
Input: K = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.
Example 2:
Input: K = 5
Output: 0
Explanation: There is no x such that x! ends in K = 5 zeroes.
Note:
K will be an integer in the range [0, 10^9].f(x) is the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * ... * x, and 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.
Note:
n and asks for the number of trailing 0s. From Problem 172, we know that the number of trailing 0s in n! depends on the number of factors of 5. If there may be K trailing 0s, then n can be at most 5 * K. Perform binary search in the interval [0, 5* K], and determine the number of trailing 0s of mid. If K can be found, then return 5; if this K cannot be found, return 0. Why can the answer only be 0 or 5? Because after n increases by 5, the number of factors of 5 increases by one again, and the trailing zeros can increase by 1 or more (if after adding 5, there are multiple factors of 5, such as 25 or 125, then the trailing zeros may increase by multiple 0s). Therefore, the range interval of n corresponding to a valid K value is 5. Conversely, the number of n corresponding to an invalid K value is 0. K will jump at the boundary of 5^n, so some values cannot be attained. For example, when n takes values in [0,5), K = 0; when n takes values in [5,10), K = 1; when n takes values in [10,15), K = 2; when n takes values in [15,20), K = 3; when n takes values in [20,25), K = 4; when n takes values in [25,30), K = 6, because 25 provides 2 factors of 5, and thus provides 2 zeros, so K can never take the value 5. That is, when K = 5, no corresponding n can be found.
package leetcode
// Solution 1: Binary search
func preimageSizeFZF(K int) int {
low, high := 0, 5*K
for low <= high {
mid := low + (high-low)>>1
k := trailingZeroes(mid)
if k == K {
return 5
} else if k > K {
high = mid - 1
} else {
low = mid + 1
}
}
return 0
}
// Solution 2: Mathematical method
func preimageSizeFZF1(K int) int {
base := 0
for base < K {
base = base*5 + 1
}
for K > 0 {
base = (base - 1) / 5
if K/base == 5 {
return 0
}
K %= base
}
return 5
}