3932. Count K-th Roots in a Range
Description
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 = 23
Example 2:
Input: l = 8, r = 30, k = 2
Output: 3
Explanation:
The perfect squares in the range[8, 30] are: 9 = 3216 = 4225 = 52
Β
Constraints:
0 <= l <= r <= 1091 <= k <= 30
Solutions
Solution 1: Enumeration
First, we check if \(k\) equals 1. If it does, the count of perfect 1st powers in the range is the count of integers in the range, which is \(r - l + 1\).
Otherwise, we enumerate integers \(x\), compute \(y = x^k\). If \(y\) exceeds \(r\), we stop enumeration. If \(y\) is within the range \([l, r]\), we increment the answer by 1.
The time complexity is \(O(r^{1/k} \cdot k)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |