In Java, to find the square root of a number is very easy if we are using the pre-defined method. Java Math class provides sqrt() method to find the square root of a number. In this section, we will create a Java program to find the square root of a number without using the sqrt() method. It is the most popular question asked in the Java interview.
If the square of a number is x, the square root of that number will be the number multiplied by itself. For example, the square root of 625 is 25. If we multiply 25 two times, we get the square of the number. Mathematically, the square root of a number is given as:
x=√x
We have used the following formula to find the square root of a number.
sqrtn+1=(sqrtn+(num/sqrtn))/2.0
Note: The first sqrt number should be the input number/2.
FindSquareRootExample1 .java
Output 1:
Output 2:
Let's see another logic to find the square root.
In the following example, we have used the following procedure to find the square root.
Binary Search Algorithm
Let's implement the algorithm in a Java program and find the square root of a number.
FindSquareRootExample2.java
Output 1:
Output 2: