I\'m trying to get the nth root of a number using JavaScript, but I don\'t see a way to do it using the built in Math
object. Am I overlooking something?
If
The n
-th root of x
is a number r
such that r
to the power of 1/n
is x
.
In real numbers, there are some subcases:
x
is positive and r
is even.x
is positive and r
is odd.x
is negative and r
is odd.x
is negative and r
is even.Since Math.pow
doesn't like a negative base with a non-integer exponent, you can use
function nthRoot(x, n) {
if(x < 0 && n%2 != 1) return NaN; // Not well defined
return (x < 0 ? -1 : 1) * Math.pow(Math.abs(x), 1/n);
}
Examples:
nthRoot(+4, 2); // 2 (the positive is chosen, but -2 is a solution too)
nthRoot(+8, 3); // 2 (this is the only solution)
nthRoot(-8, 3); // -2 (this is the only solution)
nthRoot(-4, 2); // NaN (there is no solution)