1477. Whole Kth Root

Easy1.5 points estimatedBinary SearchMaths

A tiling designer lays square, cubic or higher-dimensional blocks and needs the biggest whole edge length that does not overshoot a target size. Given a non-negative integer n and an exponent k, return the largest integer r >= 0 such that r raised to the power k is at most n.

Binary search on r. To test a candidate, multiply by r repeatedly, but stop as soon as the running product would exceed n, so nothing overflows and no floating-point power is needed. Use 64-bit integers throughout.

For example, with n = 80 and k = 4 the answer is 2, since 2^4 = 16 fits but 3^4 = 81 does not. Aim for O(k log n) time and O(1) extra space.

Example 1

Input:
n = 27, k = 3
Output:
3
Explanation:

3 cubed is exactly 27 and 4 cubed is 64, so the answer is 3.

Example 2

Input:
n = 100, k = 2
Output:
10
Explanation:

10 squared is 100, so the answer is 10.

Example 3

Input:
n = 0, k = 2
Output:
0
Explanation:

Zero is the only non-negative integer whose power fits under 0.

Constraints

0 ≤ n ≤ 1015

2 ≤ k ≤ 60

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(k log n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…