-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathO2SqrtBinSer.cpp
More file actions
44 lines (41 loc) · 816 Bytes
/
O2SqrtBinSer.cpp
File metadata and controls
44 lines (41 loc) · 816 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;
/*
This of course is a brute force solution but O(root n) complexity.
int mySqrt(int x) {
long long int i=1;
while(i*i<=x)
{
i++;
}
int ans=i-1;
return ans;
}
*/
// This is a binary search solution.
int mySqrt(int x)
{
int low=1,high=x,ans=-1;
while(low<=high)
{
int mid=(low+high)/2;
long long int msq=mid*mid;
if(msq==x)
return mid;
else if(msq>x)
high=mid-1;
else
{
low=mid+1;
ans=mid;
}
}
return ans;
}
int main()
{
// cout<<"Hello World";
int n=2147395599;
cout<<mySqrt(n);
return 0;
}