forked from abhavgoel/TribeVibe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSquareRoot.cpp
More file actions
58 lines (46 loc) · 1.05 KB
/
SquareRoot.cpp
File metadata and controls
58 lines (46 loc) · 1.05 KB
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
58
//Author: Sundar
#include <iostream>
using namespace std;
/* Question: Find the nearest possible interger value(ie floor) of the SQUARE ROOT of a number.
Example:
num=9 ans=3
num=8 ans=2 //as sqrt(8)=2.828 . Applying greatest integer function(gif)
//or finding the integer nearest and smaller than the sqrt(), we get 2
num=5 ans=2 //sqrt(5)=2.32 .. floor(2.32)=2
num=16 ans=4
num=4 ans=2
*/
//Fiding the SquareRoot using Binary Search
int squareRoot(int num)
{
if (num <= 1)
return num;
int low = 1, high = num;
int mid;
int ans = 0;
while (low <= high)
{
mid = low + (high - low) / 2;
if (mid == num / mid) //This is just mid*mid==num .
{ //Doing it this way so that we can avoid integer overflow when multiplying mid*mid
return mid;
}
else if (mid < num / mid) {
ans = mid;
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return ans;
}
int main()
{
int n;
cin >> n;
int ret = squareRoot(n);
cout << "The Square Root Rounded to integer(floor) : " << ret;
return 0;
}