Java Program to Find the Cube Root of a Given Number Using Binary Search
Last Updated :
03 Mar, 2021
Given a non-negative number find the cube root of a number using the binary search approach.
Examples :
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.
Naive Approach:
- Check the cube of every element till n and store the answer till the cube is smaller or equal to the n
Java
import java.io.*;
class GFG {
static int cuberoot( int n)
{
int ans = 0 ;
for ( int i = 1 ; i <= n; ++i) {
if (i * i * i <= n) {
ans = i;
}
}
return ans;
}
public static void main(String[] args)
{
int number = 27 ;
int cuberoot = cuberoot(number);
System.out.println(cuberoot);
}
}
|
Complexity:
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).
Algorithm:
- 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
Implementation:
Java
import java.io.*;
import java.util.*;
class GFG {
static int cuberoot( int number)
{
int left = 1 ;
int right = number;
int ans = 0 ;
while (left <= right) {
int mid = left + (right - left) / 2 ;
if (mid * mid * mid == number) {
return mid;
}
if (mid * mid * mid < number) {
left = mid + 1 ;
ans = mid;
}
else {
right = mid - 1 ;
}
}
return ans;
}
public static void main(String[] args)
{
int number = 215 ;
System.out.println(cuberoot(number));
}
}
|
Complexity:
SpaceComplexity: O(1)
TimeComplexity: O(log n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...