[removed] Calculate the nth root of a number

前端 未结 9 1438
长情又很酷
长情又很酷 2020-12-04 20:26

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

9条回答
  •  粉色の甜心
    2020-12-04 21:25

    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)
    

提交回复
热议问题