Find Square Root of a Number Without the sqrt Method in Java



In Java, we can easily find the square root of a number using the inbuilt function 'Math.sqrt()'. But sometimes during an interview, the interviewer may ask to write the code from scratch without using inbuilt functions. So in this article, we will discuss the different ways to find the square root of a number without using the sqrt method.

1.Brute Force Method

In this brute force method of calculating the square root of a number, first we check if the input is valid or not, and if the input is 0 or 1, we directly return the same number as the result without further calculation. For numbers other than 0 or 1, we find the biggest number whose square is less than or equal to the input. Then we improve the accuracy by adding smaller values starting from 0.1 until the square of the result is close to the input. Finally, we get the output rounded to 5 decimal places.

Implementation code

Below is the Java implementation of the brute force approach to finding the square root ?

public class SquareRoot {
   public static double sqrt(int input) {
      if (input < 0) {
         throw new IllegalArgumentException("Input must be non-negative.");
      }
      if (input == 0 || input == 1) {
         return input;
      }

      int i = 1;
      int check = 1;
      while (check <= input) {
         i++;
         check = i * i;
      }
      i--;

      double result = i;
      double increment = 0.1;
      while (increment >= 0.00001) {
         while (result * result <= input) {
            result += increment;
         }
         result -= increment;
         increment /= 10;
      }
      return Math.round(result * 100000.0) / 100000.0;
   }
   public static void main(String[] args) {
      int n = 16;
      System.out.println("The root of "+n+" is " +  sqrt(n));
   }
}

Output

The root of 16 is 4.0

Time Complexity

The time complexity of this code will be O(sqrt(n)) where n is the input. It contains a loop that runs approximately sqrt(n) times because i increases until the square surpasses the input.

2. Exponentiation method using Math.pow()

The Math.pow() method can be used to compute the square root by raising a number to the power of 0.5 (since the square root of a number x is x^(1/2)).

Implementation code

Below is the Java implementation using exponentiation ?

public class SquareRoot {
   public static void main(String[] args) {
      double n = 16;
      double squareRoot = Math.pow(n, 0.5);
      System.out.println("The square root of " + n + " is: " + squareRoot);
   } 
}

Output

The square root of 16.0 is: 4.0

Time Complexity

The time complexity is O(1) as Math.pow() is considered to run in constant time.

3. Newton-Raphson method

This method uses an initial guess, which is half of the number, and we guess again by averaging it with the result of dividing the original number by the guess. This is repeated until the difference between two successive guesses is very small or zero.

Example

Suppose we want to find the square root of 9:

step 1: find the first guess 9/2 =4.5
Step 2: calculate the next guess
             (4.5+(9/4.5))/2 = (4.5+2)/2 = 3.25
Step 3: Repeat again
 	(3.25+(9/3.25))/2 = (3.25+2.769)/2 = 3.0095
Step 4 : After repeating this step a few more times, we will reach close to 3, which is the actual square of 9.

Implementation code

Below is the Java implementation using the Newton-Raphson method ?

import java.util.Scanner;
class JavaExample { 
   public static double squareRoot(int number) {
      double temp;
      double sr = number / 2;
      do {
         temp = sr;
         sr = (temp + (number / temp)) / 2;
      } while ((temp - sr) != 0);
      return sr;
   }
   public static void main(String[] args) { 
      System.out.print("Enter any number:");
      Scanner scanner = new Scanner(System.in);
      int num = scanner.nextInt(); 
      scanner.close();
      System.out.println("Square root of "+ num+ " is: "+squareRoot(num));
   } 
}

Output

Enter any number: 36
Square root of 36 is: 6.0

Enter any number: 40
Square root of 40 is: 6.324555320336758

Time Complexity

The time complexity of this code is O(log n) as each iteration for calculating the guess increases logarithmically with respect to the number n.

4. Binary Search Method

This method involves finding an estimate for the square root of the number by narrowing the range between a lower and upper bound. This is repeated until the difference is very small. This can be understood with the help of an example.

Example

Suppose we have to find the square root of 16

Step 1: Initiliaze low = 1 and 
high = 16/2 + 1 = 9   
Step 2: Find mid
Mid = (low + high) / 2
Mid = (1 + 9) / 2 = 5
Step 3: Check if mid^2 is greater than 16.
	Mid^2 = 5^2 = 25 is greater than 16. So we update high=mid=5.
Step 4: calculate new mid
	Mid=(1+5)/2= 3
	Check mid^2= 3^2 =9 less than 16. So low=mid=3
Step 5: calculate mid=(3+5)/2= 4
	Check mid^2 = 4^2 =16 ,which is exactly equal to the number 16. So we stop and the answer is 4.
Step 6 : we can refine this to find a more accurate result if it exists by incrementing a small number like 0.1 and then again calculating if its square is equal to 16. But in this case, 4 is the exact square root of 16, so we stop here.

Implementation code

Below is the Java implementation using the binary search method ?

class Solution {
   public static double mySqrt(int x) {
      if (x < 0) return 0;
      if (x == 0 || x == 1) return x;
         long high = x / 2 + 1;
         long low = 1;
      while (high - low != 1) {
         long mid = low + (high - low) / 2;
         if (mid * mid > x) {
            high = mid;
         } else {
            low = mid;
         }
      }
      double result = low;
      double increment = 0.1;
      while (increment >= 0.00001) {
         while (result * result <= x) {
            result += increment;
         }
         result -= increment;
         increment /= 10;
      }
      return Math.round(result * 100000.0) / 100000.0;
   }
   public static void main(String[] args) {
      int n = 16; // Initialize n
      double result = mySqrt(n); 
      System.out.println("The square root of " + n + " is: " + result);
   }  
}

Output

When n=49,
The square root of 49 is: 7.0
When n=50,
The square root of 50 is: 7.07106

Time Complexity

The time complexity of this algorithm is O(log n) as the binary search reduces the range of values by half with each step.

Updated on: 2025-02-27T13:15:02+05:30

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements