Created
August 22, 2017 00:49
-
-
Save thinkxacademy/1c40a13185e49fc8a5072845776faf92 to your computer and use it in GitHub Desktop.
Algorithm to find square root of a number using Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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