Finding Square root using Binary Search

Palakkgoyal
1 min readDec 12, 2022

--

Today we are going to see how we can find the square root of any number without using the inbuilt method.

public class BinarySearchSQRT{
public static void main(String[] args) {
int n = 40;

//this p is precesion it means till how many decimal points we want our answer to be
int p = 3;

System.out.printf("%.3f",SQRT(n,p));

}

static double SQRT(int n, int p){

//As we are going to search in sorted numbers so we will use binary search
int s = 1;
int e = n/2;

double root = 0.0;

while(s <= e){
int m = s + (e-s)/2;

if(m*m == n){
return m;
}
else if(m*m < n){
s = m+1;
}
else{
e = m-1;
}
}

root = e;
double incr = 0.1;

//now get the precision
for(int i = 0; i < p; i++){
while(root*root <= n){
root += incr;
}
root -= incr;

incr /= 10;
}

return root;
}
}

Time complexity:- O(log n)

Space complexity:- O(1)

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.