Javatpoint Logo
Javatpoint Logo

Java Program to Find Square Root of a Number Without sqrt Method

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.

Let's implement the above formula in a Java program and find the square root.

FindSquareRootExample1 .java

Output 1:

Enter a number: 12
The square root of 12 is: 3.4641016151377544

Output 2:

Enter a number: 25
The square root of 25 is: 5.0

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.

  • We have initialized an iterator variable i=1.
  • Check the number that we have entered is a perfect square or not. If the square of i is equal to n, i will be the square root value of n.
  • Otherwise, find the lowest value of i. Remember that the square of i must be greater than n. The square root of a number lies between i-1 and i. After performing the steps, we use the binary search algorithm to find the square root of a number up to n decimal places.
  • Increment the variable i by 1.

Binary Search Algorithm

  • Find the midvalue of i-1 and i.
  • Find the square of midvalue and compare it with n.
    • If midvalue * midvalue = n, the midvalue is the square root of the given number. Compare the square of midvalue with n (up to n decimal places) if the difference is minor, the midvalue will be the square root of the number.
    • If midvalue * midvalue > n, the square root belongs to the first half.
    • If midvalue * midvalue < n, the square root belongs to the second half.

Let's implement the algorithm in a Java program and find the square root of a number.

FindSquareRootExample2.java

Output 1:

Enter a number: 625
The square root of 625.0 is 25.0

Output 2:

Enter a number: 129
The square root of 129.0 is 11.357816688716412

Next TopicJava Tutorial





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA