programming-examples/js/Math/Calculate the nth root of a number.js

13 lines
372 B
JavaScript
Raw Normal View History

2019-11-15 12:59:38 +01:00
function nthroot(x, n)
{
ng = n % 2;
if((ng == 1) || x<0)
x = -x;
var r = Math.pow(x, 1 / n);
n = Math.pow(r, n);
if(Math.abs(x - n) < 1 && (x > 0 === n > 0))
return ng ? -r : r;
}
console.log(nthroot(64, 2));
console.log(nthroot(64, -2));