-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0793-preimage-size-of-factorial-zeroes-function.js
69 lines (57 loc) · 1.42 KB
/
0793-preimage-size-of-factorial-zeroes-function.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* 793. Preimage Size of Factorial Zeroes Function
* https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/
* Difficulty: Hard
*
* 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 two zeroes at the end.
*
* Given an integer k, return the number of non-negative integers x have the property that f(x) = k.
*/
/**
* @param {number} k
* @return {number}
*/
var preimageSizeFZF = function(k) {
return findUpperBound(k) - findLowerBound(k);
};
function findLowerBound(k) {
let left = 0;
let right = 5 * (10 ** 10);
while (left < right) {
const mid = Math.floor((left + right) / 2);
const zeroes = countTrailingZeroes(mid);
if (zeroes < k) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
function findUpperBound(k) {
let left = 0;
let right = 5 * (10 ** 10);
while (left < right) {
const mid = Math.floor((left + right) / 2);
const zeroes = countTrailingZeroes(mid);
if (zeroes <= k) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
function countTrailingZeroes(n) {
let count = 0;
let powerOfFive = 5;
while (n >= powerOfFive) {
count += Math.floor(n / powerOfFive);
powerOfFive *= 5;
}
return count;
}