n 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:
- There are two solutions (same value with opposite sign) when
x is positive and r even. - There is one positive solution when
x positive and r is odd. - There is one negative solution when
x negative and r is odd. - There is no solution when
x negative and r is even.
Since Math.pow does not like a negative base with a non-integer metric, you can use
function nthRoot(x, n) { if(x < 0 && n%2 != 1) return NaN;
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)
Oriol Feb 29 '16 at 1:01 2016-02-29 01:01
source share