Skip to content

Instantly share code, notes, and snippets.

@abhishek2x
Last active December 19, 2020 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhishek2x/ff8946352df62b8d85c8611aa6723eac to your computer and use it in GitHub Desktop.
Save abhishek2x/ff8946352df62b8d85c8611aa6723eac to your computer and use it in GitHub Desktop.
Finding Square root using Binary Search Algorithm
/*!
* 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