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:
There are two solutions (same value with opposite sign) when x is positive and r is even.
There is one positive solution when x is positive and r is odd.
There is one negative solution when x is negative and r is odd.
There is no solution when 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)
Here's a function that tries to return the imaginary number. It also checks for a few common things first, ex: if getting square root of 0 or 1, or getting 0th root of number x
function root(x, n){
if(x == 1){
return 1;
}else if(x == 0 && n > 0){
return 0;
}else if(x == 0 && n < 0){
return Infinity;
}else if(n == 1){
return x;
}else if(n == 0 && x > 1){
return Infinity;
}else if(n == 0 && x == 1){
return 1;
}else if(n == 0 && x < 1 && x > -1){
return 0;
}else if(n == 0){
return NaN;
}
var result = false;
var num = x;
var neg = false;
if(num < 0){
//not using Math.abs because I need the function to remember if the number was positive or negative
num = num*-1;
neg = true;
}
if(n == 2){
//better to use square root if we can
result = Math.sqrt(num);
}else if(n == 3){
//better to use cube root if we can
result = Math.cbrt(num);
}else if(n > 3){
//the method Digital Plane suggested
result = Math.pow(num, 1/n);
}else if(n < 0){
//the method Digital Plane suggested
result = Math.pow(num, 1/n);
}
if(neg && n == 2){
//if square root, you can just add the imaginary number "i=√-1" to a string answer
//you should check if the functions return value contains i, before continuing any calculations
result += 'i';
}else if(neg && n % 2 !== 0 && n > 0){
//if the nth root is an odd number, you don't get an imaginary number
//neg*neg=pos, but neg*neg*neg=neg
//so you can simply make an odd nth root of a negative number, a negative number
result = result*-1;
}else if(neg){
//if the nth root is an even number that is not 2, things get more complex
//if someone wants to calculate this further, they can
//i'm just going to stop at *n√-1 (times the nth root of -1)
//you should also check if the functions return value contains * or √, before continuing any calculations
result += '*'+n+√+'-1';
}
return result;
}
Well, I know this is an old question. But, based on SwiftNinjaPro's answer, I simplified the function and fixed some NaN issues. Note: This function used ES6 feature, arrow function and template strings, and exponentation. So, it might not work in older browsers: