Medium
You are given three integers l, r, and k.
An integer y is said to be a perfect kth power if there exists an integer x such that y = xk.
Return the number of integers y in the range [l, r] (inclusive) that are perfect kth powers.
Example 1:
Input: l = 1, r = 9, k = 3
Output: 2
Explanation:
The perfect cubes in the range [1, 9] are:
1 = 138 = 23Hence, the answer is 2.
Example 2:
Input: l = 8, r = 30, k = 2
Output: 3
Explanation:
The perfect squares in the range [8, 30] are:
9 = 3216 = 4225 = 52Hence, the answer is 3.
Constraints:
0 <= l <= r <= 1091 <= k <= 30import kotlin.math.pow
class Solution {
fun countKthRoots(l: Int, r: Int, k: Int): Int {
if (k == 1) {
return r - l + 1
}
var ans = 0
var start = 0
var pow = start.toDouble().pow(k.toDouble()).toInt()
while (l > pow) {
start++
pow = start.toDouble().pow(k.toDouble()).toInt()
}
while (pow <= r) {
start++
pow = start.toDouble().pow(k.toDouble()).toInt()
ans++
}
return ans
}
}