-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompute_square_root.h
More file actions
40 lines (34 loc) · 983 Bytes
/
Copy pathcompute_square_root.h
File metadata and controls
40 lines (34 loc) · 983 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
#ifndef CPP_ALGORITHM_COMPUTE_SQUARE_ROOT_H
#define CPP_ALGORITHM_COMPUTE_SQUARE_ROOT_H
namespace ComputeSquareRoot
{
/**
* \brief Compute the integer square root of a number.
* \details When given a non-negative integer,
* return the largest integer whose square is less than or equal to the number.
* \param k non-negative integer
* \return largest integer whose square is less than or equal to the number
*/
int ComputeIntegerSquareRoot(int k);
}
// ----------------------------------------------------------------------------
inline int ComputeSquareRoot::ComputeIntegerSquareRoot(const int k)
{
int left = 0;
int right = k;
while (left <= right)
{
const int mid = left + (right - left) / 2;
const int mid_squared = mid * mid;
if (mid_squared <= k)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return left - 1;
}
#endif