Skip to main content

3.2 Calculating Square Root

69. Sqrt(x)​

Problem Description​

Given a non-negative integer x, calculate its square root and round it down to the nearest integer.

Input and Output Example​

The input is an integer, and the output is also an integer.

Input: 8
Output: 2

The square root of 8 is 2.82842..., and rounding it down gives 2.

Solution Explanation​

We can think of this problem as: given a non-negative integer x, find the solution to f(t)=t2−x=0f(t) = t^2 − x = 0. Since we only consider t≥0t ≥ 0, f(t)f(t) is monotonically increasing in its domain. Given that f(0)=−x≤0f(0) = −x ≤ 0 and f(x)=x2−x≥0f(x) = x^2 − x ≥ 0, we can use binary search on the interval [0,x][0, x] to find the solution where f(t)=0f(t) = 0. Here, we adopt a left-closed, right-closed approach.

In the C++ solution, using mid=(l+r)/2mid = (l + r) / 2 might result in overflow due to l+rl + r, so we use mid=l+(r−l)/2mid = l + (r − l) / 2 instead. Directly calculating mid∗midmid ∗ mid might also overflow, so we compare midmid with x/midx / mid instead.

int mySqrt(int x) {
int l = 1, r = x, mid, x_div_mid;
while (l <= r) {
mid = l + (r - l) / 2;
x_div_mid = x / mid;
if (mid == x_div_mid) {
return mid;
}
if (mid < x_div_mid) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return r;
}

Additionally, this problem can be solved using a faster algorithm—Newton's Iterative Method. The formula is tn+1=tn−f(tn)f′(tn)t_{n+1} = t_n - \frac{f(t_n)}{f'(t_n)}. For f(t)=t2−x=0f(t) = t^2 − x = 0, the iteration formula becomes tn+1=tn+xtn2t_{n+1} = \frac{t_n + \frac{x}{t_n}}{2}.

int mySqrt(int x) {
long t = x;
while (t * t > x) {
t = (t + x / t) / 2;
}
return t;
}