Java Program to Find the Cube Root of a Given Number Using Binary Search
Given a non-negative number find the cube root of a number using the binary search approach.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: x = 27 Output: 3 Explanation: The cube root of 16 is 4. Input: x = 120 Output: 4 Explanation: The cube root of 120 lies in between 4 and 5 so floor of the cube root is 4.
- Check the cube of every element till n and store the answer till the cube is smaller or equal to the n
SpaceComplexity: O(1) TimeComplexity: O(n)
Efficient Approach (Binary Search):
Binary Search used Divide and Conquer approach that makes the complexity is O(log n).
- Initialize left=0 and right =n
- Calculate mid=left+(right-left)/2
- If mid*mid*mid is equal to the number return the mid
- If mid*mid*mid is less than the number store the mid in ans and increase left=mid+1
- If mid*mid*mid is more than the number and decrease the right=mid-1
- Return the answer
SpaceComplexity: O(1) TimeComplexity: O(log n)