[LeetCode] Count K-th Roots in a Range

3932. Count K-th Roots in a Range

You are given three integers l, r, and k.

An integer y is said to be a perfect k^th power if there exists an integer x such that y = x^k.

Return the number of integers y in the range [l, r] (inclusive) that are perfect k^th powers.

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
class Solution {
long long helper(long long m, long long k, long long lim) {
long long x = 1;
for(int i = 0; i < k and x <= lim; i++) {
x = x * m;
}
return x <= lim;
}
long long helper(long long n, long long k) {
if(n <= 0) return 0;
long long l = 1, r = n, res = 0;
while(l <= r) {
long long m = l + (r - l) / 2;
bool ok = helper(m,k,n);
if(ok) {
l = m + 1;
res = m;
} else r = m - 1;
}

return res;
}
public:
int countKthRoots(int l, int r, int k) {
return helper(r,k) - helper(l-1,k) + !l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/count-k-th-roots-in-a-range/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.