562.Count Iterations When Dividing by K
Easy
For the loop
while (n > 0) { n /= k; }, return how many times it runs for the given n and k.
A loop whose variable is divided by a constant each time is logarithmicLogarithmic LoopA loop whose variable is multiplied or divided by a constant each pass, so it runs about log(n) times.: the number of passes is the number of digits of n in base k, roughly log_k(n). The base only changes a constant factor (log₁₀ n vs log₂ n), so all such loops are simply O(log n).
Example 1:
Input: n = 1000, k = 10
Output: 4
Example 2:
Input: n = 8, k = 2
Output: 4
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ n ≤ 1000000000 - ●
2 ≤ k ≤ 10
n =
1000
k =
10