Using Mathematical properties of Log.
Considering ‘n’th root of ‘m’ means there exits a certain variable ‘a’ such that:
a^(n) = m
Applying Log on both sides:
log(a^n) = log(m)
Modifying it further gives us:
a = e^(log m / n)
which in code terms is represented as:
double a = Math.pow(Math.E, (Math.log(m)/n));
Then check for double infinitive and return int.
import java.util.*;
public class Solution {
public static int NthRoot(int n, int m) {
double a = Math.pow(Math.E, (Math.log(m)/n));
if (Math.ceil(a) - a < 0.000000001) return (int) Math.ceil(a);
else if (a - Math.floor(a) < 0.000000001) return (int) Math.floor(a);
if ((a == Math.floor(a)) && !Double.isInfinite(a)) {
return (int) a;
}
return -1;
}
}