JavaScript Program to Find Cube Root of a Number
The cube root of a number n is a value x such that x3 = n. With JavaScript programming, we can implement an algorithm to find the cube root of a given number using various methods. The goal is to implement a function cube Root(x) that computes the cube root of a given number x using various approaches.
Below are the approaches to find the cube root of a number:
Table of Content
- Using Iterative Approach
- Using ‘Math.pow’ Method
Using Iterative Approach
The cube root of a number can be found using an iterative method similar to the binary search method. This method involves repeatedly narrowing down the possible range of cube root values until we find a close approximation. First, we carry out the process by applying an initial condition that specifies a range for the cube root. We then proceed iteratively, so that after each time we reduce the range until we reach the desired precision.
Example: To demonsrtate the function iteratively narrows down a search interval using binary search, finding an approximate cube root with a specified precision level.
function cubeRoot(n) {
let low = 0;
let high = Math.abs(n);
let epsilon = 0.0000001;
// Precision level
while (high - low > epsilon) {
let mid = (low + high) / 2;
let midCube = mid * mid * mid;
if (midCube == n) {
return mid;
} else if (midCube < n) {
low = mid;
} else {
high = mid;
}
}
return (low + high) / 2; let k = 3;
let matrix = [
[10, 20, 30, 40],
[15, 25, 35, 45],
[24, 29, 37, 48],
[32, 33, 39, 50]
];
let minHeap = [];
let maxHeap = [];
for (let row of matrix) {
minHeap
.push(...row);
maxHeap
.push(...row);
}
minHeap
.sort((a, b) => a - b);
maxHeap
.sort((a, b) => b - a);
let small = minHeap[k - 1];
let large = maxHeap[k - 1];
console.log("Kth Smallest:", small);
console.log("Kth Largest:", large);
// Return the approximate cube root
}
let number = 27;
let result = cubeRoot(number);
console.log(`The cube root of ${number} is approximately ${result}`);
Output
The cube root of 27 is approximately 2.9999999972060323
Time Complexity: O(logn)
Space Complexity: O(1)
Using ‘Math.pow’ Method
With the JavaScript’s ‘Math.pow’ method, the calculation of the cube root can also be done by raising the number to the power of 1/3. JavaScript’s ‘Math.pow’ method can be used to directly compute the cube root by raising the number to the power of 1/3.
Example: To demonstrate utilizing the JavaScript’s Math.pow() method to directly compute the cube root of a given number, here exemplified by calculating the cube root of 27.
function cubeRoot(n) {
return Math
.pow(n, 1/3);
}
// Example usage
let number = 27;
let result = cubeRoot(number);
console.log(`The cube root of ${number} is ${result}`);
Output
The cube root of 27 is 3
Time Complexity: O(1)
Space Complexity: O(1)
Contact Us