Nth Root by Binary Search
MediumP3Coding
Given two positive integers n and m, return the integer x such that x raised to the power n equals m. If no such integer exists, return -1.
Use binary search on x; do not use floating-point root functions.
Example 1
- Input
- n = 3, m = 27
- Output
- 3
Example 2
- Input
- n = 4, m = 69
- Output
- -1
Example 3
- Input
- n = 1, m = 5
- Output
- 5
Constraints
- 1 <= n <= 30
- 1 <= m <= 10^9
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 12. ⌘Enter runs, ⌘⇧Enter submits.