Table of Contents
Input-output example
Binary search
Example of using binary search to find a key
question
solution
Algorithm for finding cube roots using binary search
Example
Output
Home Java javaTutorial Java program to find the cube root of a number using binary search algorithm

Java program to find the cube root of a number using binary search algorithm

Aug 28, 2023 pm 01:33 PM
java program cube root binary search

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 
Copy after login

For example, the cube root of 64 is 4, and the output is 4.

Example-2: 
Input: 216
Output: 6  
Copy after login

For example, the cube root of 216 is 6, and the output is 6.

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.

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 of

Example

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);
   }
}
Copy after login

Output

Cube root of 64 = 4 
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java program opens command prompt and inserts command Java program opens command prompt and inserts command Aug 19, 2023 pm 12:29 PM

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

Java program used to check if TPP students are eligible for interviews Java program used to check if TPP students are eligible for interviews Sep 06, 2023 pm 10:33 PM

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

Java program to get the size of a given file in bytes, kilobytes and megabytes Java program to get the size of a given file in bytes, kilobytes and megabytes Sep 06, 2023 am 10:13 AM

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

Write a Java program to calculate the area and perimeter of a rectangle using the concept of classes Write a Java program to calculate the area and perimeter of a rectangle using the concept of classes Sep 03, 2023 am 11:37 AM

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

Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Aug 20, 2023 pm 10:49 PM

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 write a binary search algorithm using C# How to write a binary search algorithm using C# Sep 19, 2023 pm 12:42 PM

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

JAVA program to convert Roman numerals to integer numbers JAVA program to convert Roman numerals to integer numbers Aug 25, 2023 am 11:41 AM

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

Java program to create pyramids and patterns Java program to create pyramids and patterns Sep 05, 2023 pm 03:05 PM

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+

See all articles