-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathSqrt(x).cpp
57 lines (49 loc) · 1.26 KB
/
Sqrt(x).cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
using namespace std;
int floorSqrt(int x)
{
// Base cases
if (x == 0 || x == 1)
return x;
// Do Binary Search for floor(sqrt(x))
int start = 1, end = x / 2, ans;
while (start <= end)
{
int mid = (start + end) / 2;
// If x is a perfect square
int sqr = mid * mid;
if (sqr == x)
return mid;
// Since we need floor, we update answer when
// mid*mid is smaller than x, and move closer to
// sqrt(x)
/*
if(mid*mid<=x)
{
start = mid+1;
ans = mid;
}
Here basically if we multiply mid with itself so
there will be integer overflow which will throw
tle for larger input so to overcome this
situation we can use long or we can just divide
the number by mid which is same as checking
mid*mid < x
*/
if (sqr <= x)
{
start = mid + 1;
ans = mid;
}
else // If mid*mid is greater than x
end = mid - 1;
}
return ans;
}
// Driver program
int main()
{
int x = 11;
cout << floorSqrt(x) << endl;
return 0;
}