w3resource

JavaScript: Calculate the nth root of a number

JavaScript Math: Exercise-26 with Solution

Calculate nth Root of a Number

Write a JavaScript function to calculate the nth root of a number.

Test Data :
console.log(nthroot(64, 2));
8
console.log(nthroot(64, -2));
0.125

Sample Solution:

JavaScript Code:

// Define a function named nthroot that calculates the nth root of a given number.
function nthroot(x, n)
{
    // Determine if n is odd.
    ng = n % 2;
    // If n is odd or x is negative, make x positive.
    if((ng == 1) || x<0)
        x = -x;
    // Calculate the nth root of x.
    var r = Math.pow(x, 1 / n);
    // Raise r to the power of n.
    n = Math.pow(r, n);
  
    // Check if the difference between x and n is less than 1 and both x and n have the same sign.
    if(Math.abs(x - n) < 1 && (x > 0 === n > 0))
        // If n is odd, return -r, otherwise return r.
        return ng ? -r : r; 
}

// Output the result of calculating the square root of 64 to the console.
console.log(nthroot(64, 2));
// Output the result of calculating the square root of 64 with negative exponent to the console.
console.log(nthroot(64, -2));

Output:

8
0.125

Visual Presentation:

JavaScript: Math - Calculate the nth root of a number.

Flowchart:

Flowchart: JavaScript Math- Calculate the nth root of a number

Live Demo:

See the Pen javascript-math-exercise-26 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that calculates the nth root of a number using exponentiation and handles fractional exponents.
  • Write a JavaScript function that implements the nth root calculation iteratively using the Newton-Raphson method.
  • Write a JavaScript function that validates inputs for nth root calculation and returns an error for invalid parameters.
  • Write a JavaScript function that calculates the nth root and returns the result rounded to a specified precision.

Go to:


PREV : Currency Math Operations.
NEXT : Calculate Degrees Between Two Points.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.