Finding Square root using Binary Search

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)

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Palakkgoyal

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