← DiffPush

Nth root of integer

Baseline Binary Search · In Search Space O(log m) · O(1)

Equal-Splitting a Battery Bank

A hardware team must arrange m identical cells into a perfect n-sided array where every leg holds the same count - that is, m must be an exact nth power. When the arrangement is impossible, the planner reports failure instead of rounding. Decide whether an integer root exists and return it.

Input: Two integers n (the root degree) and m (the target value).

Output: The integer r with r^n == m, or -1 when m has no integer nth root.

Constraints

Examples

Example 1

Input: {"n":2,"m":9}
Output: 3
Three legs of three cells each form the array exactly, since 3 squared is 9.

Example 2

Input: {"n":3,"m":9}
Output: -1
No integer cubed equals 9, so the arrangement is impossible and -1 is returned.

Solve this in your browser →

Also on LeetCode ↗