Java program to find the cube root of a number using binary search algorithm
Cube root is an integer value that, when multiplied by itself three times in succession, results in the original value. In this article, we will write a Java program that uses binary search to find the cube root of a number. Finding the cube root of a number is an application of the binary search algorithm. In this article, we will discuss in detail how to use binary search to calculate cube roots.
Input-output example
Example-1: Input: 64 Output: 4
For example, the cube root of 64 is 4, and the output is 4.
Example-2: Input: 216 Output: 6
For example, the cube root of 216 is 6, and the output is 6.
Binary search
Binary search is an algorithm used to find elements (i.e. keys in a sorted array). The working principle of binary algorithm is as follows
Assume the array is "arr". Sort an array in ascending or descending order.
Initialize low = 0 and high = n-1 (n = number of elements), and calculate mid as middle = low (high-low)/2. If arr[middle] == key then returns middle, the middle index of the array.
If the key value is less than the arr[middle] element, set the high index to the middle index -1; if the key value is greater than the middle element, set the low index to the middle index 1
Continue binary search until you find the element you want to find.
If low is greater than high, return false directly because the key value does not exist in the array 'arr'.
Example of using binary search to find a key
question
Given an ordered integer array arr = [1, 3, 5, 7, 9, 11], use binary search to find the index of the element, that is, key = 7.
solution
Initialize low = 0 and high = 5 (last index of the array).
The first iteration of the while loop gives the middle index mid = low (high-low)/2
Median = 0 (5-0)/2 = 2.
The value of arr[mid] is 5, which is less than the key value 7. Therefore, we update low= mid 1 = 3.
The second iteration of the while loop gives us the mid index mid = 4 by using low (high-low)/2.
The value of arr[mid] is 9, which is greater than the key value 7. Therefore, we update high = 3 (mid - 1).
The third iteration of the while loop gives us the mid index mid = 3.
arr[mid] is 7, equal to the key value. Therefore, we return the middle index, which is 3.
So, in the given array, the index of the keyword is 7, and we found the index 3 using the binary search algorithm.
Algorithm for finding cube roots using binary search
Step 1 - Consider a number 'n' and initialize low=0 and right=n (the given number).
Step 2 - Find the median of low and high values using mid = low (high-low)/2.
Step 3 − Find the value of mid * mid * mid. If mid * mid * mid == n, return the value of mid.
Step 4 - If the middle value is less than n, then low=mid 1, otherwise high=mid-1
Step 5 - Repeat steps 2 through 4 until you find the value.
The Chinese translation ofExample
is:Example
In this example, we use the binary search algorithm to find the cube root of a value. We created a custom class 'BinarySearchCbrt' and implemented the binary search code for finding the cube root of a number in the 'cuberoot' function. Now, create a custom class object and initialize an integer variable named 'number' and call the 'cuberoot' function using the class object, thereby displaying the desired output.
//Java Program to find Cube root of a number using Binary Search import java.util.*; class BinarySearchCbrt { public int cuberoot(int number) { int low = 0; int high = number; while (low <= high) { int mid = (low + high) / 2; int cube = mid * mid*mid; if (cube == number) { return mid; } else if (cube < number) { low = mid + 1; } else { high = mid - 1; } } return 0; } } public class Main { public static void main(String[] args) { int n = 64; BinarySearchCbrt Obj = new BinarySearchCbrt(); int result= Obj.cuberoot(n); System.out.println("Cube root of " + n + " = " + result); } }
Output
Cube root of 64 = 4
Time complexity: O(NlogN) Auxiliary space: O(1)
So, in this article we have discussed how to find the cube root of a number using binary search algorithm in Java.
The above is the detailed content of Java program to find the cube root of a number using binary search algorithm. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



ThisarticleusesvariousapproachesforselectingthecommandsinsertedintheopenedcommandwindowthroughtheJavacode.Thecommandwindowisopenedbyusing‘cmd’.Here,themethodsofdoingthesamearespecifiedusingJavacode.TheCommandwindowisfirstopenedusingtheJavaprogram.Iti

Please consider the table below to know the eligibility criteria of different companies - The Chinese translation of CGPA is: GPA greater than or equal to 8 Eligible companies Google, Microsoft, Amazon, Dell, Intel, Wipro greater than or equal to 7 Tutorial points, accenture, Infosys , Emicon, Rellins greater than or equal to 6rtCamp, Cybertech, Skybags, Killer, Raymond greater than or equal to 5Patronics, Shoes, NoBrokers Let us enter the java program to check the eligibility of tpp students for interview. Method 1: Using ifelseif condition Normally when we have to check multiple conditions we use

The size of a file is the amount of storage space that a specific file takes up on a specific storage device, such as a hard drive. The size of a file is measured in bytes. In this section, we will discuss how to implement a java program to get the size of a given file in bytes, kilobytes and megabytes. A byte is the smallest unit of digital information. One byte equals eight bits. One kilobyte (KB) = 1,024 bytes, one megabyte (MB) = 1,024KB, one gigabyte (GB) = 1,024MB and one terabyte (TB) = 1,024GB. The size of a file usually depends on the type of file and the amount of data it contains. Taking a text document as an example, the file size may be only a few kilobytes, while a high-resolution image or video file may be

The Java language is one of the most commonly used object-oriented programming languages in the world today. The concept of classes is one of the most important features of object-oriented languages. A class is like a blueprint for an object. For example, when we want to build a house, we first create a blueprint of the house, in other words, we create a plan that shows how we are going to build the house. According to this plan we can build many houses. Likewise, using classes, we can create many objects. Classes are blueprints for creating many objects, where objects are real-world entities like cars, bikes, pens, etc. A class has the characteristics of all objects, and the objects have the values of these characteristics. In this article, we will write a Java program to find the perimeter and faces of a rectangle using the concept of classes

Inheritance is a concept that allows us to access the properties and behavior of one class from another class. The class that inherits methods and member variables is called a superclass or parent class, and the class that inherits these methods and member variables is called a subclass or subclass. In Java, we use "extends" keyword to inherit a class. In this article, we will discuss a Java program to calculate interest on fixed deposits and time deposits using inheritance. First, create these four Java files - Acnt.java − in your local machine IDE. This file will contain an abstract class ‘Acnt’ which is used to store account details like interest rate and amount. It will also have an abstract method 'calcIntrst' with parameter 'amnt' for calculating

How to use C# to write a binary search algorithm. The binary search algorithm is an efficient search algorithm. It finds the position of a specific element in an ordered array with a time complexity of O(logN). In C#, we can write the binary search algorithm through the following steps. Step 1: Prepare data First, we need to prepare a sorted array as the target data for the search. Suppose we want to find the position of a specific element in an array. int[]data={1,3,5,7,9,11,13

Roman Numerals - Based on the ancient Roman system that uses symbols to represent numbers. These numbers are called Roman numerals. The symbols are I, V, X, L, C, D and M, which represent 1, 5, 10, 50, 100, 500 and 1,000 respectively. Integers - An integer is an integer consisting of positive, negative and zero values. Fractions are not whole numbers. Here we set the symbol value based on the integer value. Whenever a Roman numeral is given as input, we divide it into units and then calculate the appropriate Roman numeral. I-1II–2III–3IV–4V–5VI–6…X–10XI–11..XV-15 In this article, we will learn how to convert Roman numerals to integers in Java. Show you some examples - Example 1InputR

If anyone wants to get a solid foundation in Java programming language. Then, it is necessary to understand how the loop works. Furthermore, solving Pyramid Pattern problems is the best way to enhance your knowledge of Java basics as it includes extensive use of for and while loops. This article aims to provide some Java programs to print pyramid patterns with the help of different types of loops available in Java. Java Program to Create Pyramid Pattern We will print the following pyramid patterns through Java program - Inverted Star Pyramid Star Pyramid Number Pyramid Let's discuss one by one. Mode 1: The inverted star pyramid method declares and initializes an integer "n" with the specified number of rows. Next, define the initial count of the space as 0 and the initial count of the star as "n+
