Last active
December 19, 2020 13:00
-
-
Save abhishek2x/ff8946352df62b8d85c8611aa6723eac to your computer and use it in GitHub Desktop.
Finding Square root using Binary Search Algorithm
This file contains 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
/*! | |
* Copyright (c) 2020 Abhishek Srivastava | |
*/ | |
/* | |
For demstration of concept we are using | |
int variable. But ideally we will prefer using | |
double value with an Epison error estimation. | |
*/ | |
#include <bits/stdc++.h> | |
using namespace std; | |
#define ll long long int | |
int getSquareRoot(int n, int start, int end) { | |
if (start > end) | |
return -1; | |
int mid = start + (end-start)/2; | |
if(mid*mid == n){ | |
return mid; | |
} else if(mid*mid > n) { | |
getSquareRoot(n, start, end-1); | |
} else getSquareRoot(n ,start+1, end); | |
} | |
int main(){ | |
ios :: sync_with_stdio(false); | |
cin.tie(0); | |
int n; cin >> n; | |
cout << getSquareRoot(n, 0, n/2); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment