Skip to content

Instantly share code, notes, and snippets.

Last active Dec 19, 2020
What would you like to do?
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);
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