w3resource

JavaScript: Iterated Cube Root

JavaScript Math: Exercise-92 with Solution

Cube Root Reduction Steps

Write a Python program that takes a positive integer and calculates the cube root of the number until it is less than three. Return the number of steps to complete this process.

Test Data:
(27) -> 2
(10000) -> 2
(-100) -> "Not a positive number!"

Sample Solution:

JavaScript Code:

/**
 * Function to calculate the number of iterations required to find the cube root of a number greater than or equal to 3.
 * @param {number} n - The number for which cube root iterations are to be performed.
 * @returns {number|string} - The number of iterations required to find the cube root, or a string indicating that the input is not a positive number.
 */
function test(n) {
    let ctr = 0;
    while (n >= 3) {
        n =  n ** (1./3.);
        ctr = ctr + 1;
    }
    if (n < 0)
        return 'Not a positive number!';
    else 
        return ctr;
} 

// Test cases
console.log("Iterated Cube Root:");
let n = 27;
console.log("n = "+n);
console.log("Number of steps to complete the said process: "+test(n));
n = 10000;
console.log("n = "+n);
console.log("Number of steps to complete the said process: "+test(n));
n = -100;
console.log("n = "+n);
console.log("Number of steps to complete the said process: "+test(n));

Output:

Iterated Cube Root:
n = 27
Number of steps to complete the said process: 2
n = 10000
Number of steps to complete the said process: 2
n = -100
Number of steps to complete the said process: Not a positive number!

Flowchart:

JavaScript: Iterated Cube Root.

Live Demo:

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


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that repeatedly computes the cube root of a positive integer until the result is less than three, returning the number of steps.
  • Write a JavaScript function that uses a while loop to perform cube root reduction and counts the iterations required.
  • Write a JavaScript function that recursively computes the cube root reduction steps and returns the total number of recursive calls.
  • Write a JavaScript function that validates input as a positive number before performing cube root reduction and step counting.

Go to:


PREV : Sum of Odd Elements in Matrix.
NEXT : Check Downward Trend in Array.

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.