Find the Integer Nth Root of a Number (or Report It Doesn't Exist)
Implement nthRoot
Given two positive integers
m and n, find the positive integer x such that x raised to the power n equals m exactly, or return -1 if no such integer exists.
Raising a number to a fixed power is strictly increasing: as x grows, x^n only ever grows with it, never dips back down. That means the candidates 1 through m split cleanly into three zones — too small, exactly right, and too big — in that order, which is exactly the monotonic structure a binary search on the answerBinary Search on the AnswerThe search runs directly over the space of candidate answers rather than over an array. It applies whenever a computed property of the candidate — here, the candidate raised to the n-th power — moves in one direction as the candidate grows. needs: binary search the candidate roots directly, narrowing toward whichever one lands exactly on m — or concluding none does.
Example 1:
Input: m = 64, n = 3
Output: 4
Example 2:
Input: m = 81, n = 4
Output: 3
Example 3:
Input: m = 10, n = 2
Output: -1
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ m ≤ 10⁹ - ●
1 ≤ n ≤ 30
m =
64
n =
3