#include <iostream>
using namespace std;
long long int binarySearch(int arr[],int n,int key) {
int start = 0;
int end = n-1;
long long int mid = start + (end-start)/2;
long long int ans = -1;
while (start <= end){
long long int square = mid*mid;
if (square == key) {
return mid;
}
else if (square > key) {
end = mid - 1;
}
else {
start = mid + 1;
ans = mid;
}
mid = start + (end-start)/2;
}
return ans;
}
int main() {
int n;
cout << "enter the number :" << endl;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = (i+1);
}
int squareRoot = binarySearch(arr,n,n);
cout << "square root of " << n << " is " << squareRoot << endl;
return 0;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter