Skip to content

Instantly share code, notes, and snippets.

@thinkxacademy
Created August 22, 2017 00:49
Show Gist options
  • Select an option

  • Save thinkxacademy/1c40a13185e49fc8a5072845776faf92 to your computer and use it in GitHub Desktop.

Select an option

Save thinkxacademy/1c40a13185e49fc8a5072845776faf92 to your computer and use it in GitHub Desktop.
Algorithm to find square root of a number using Binary Search
//A Program for displaying the square root of a number using binary search.
#include<stdio.h>
#include<stdlib.h>
float binarySearchSquareRoot(int n,int p)
{ int s=0;
int e=n;
float a;int mid;
while(s<=e){
mid=(e+s)/2;
if(mid*mid == n){
a = mid;break;
}
if(mid*mid<n){
s=mid +1;
a = mid;
}
else{
e = mid-1;
}
}
//Fractional part
float inc =0.1;
for(int i=0;i<p;i++){
while(a*a<=n)
{
a += inc;
}
//a * a >n;
a =a -inc;
inc = inc/10;
}
return a;
}
int main()
{ float ans;
ans= binarySearchSquareRoot(765,5);
printf("%f",ans);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment