69 Sqrt(x)

Implementint sqrt(int x).

Compute and return the square root of x.

The Idea: The naive solution would be to return the first index in the for loop through x where ii=xi*i=x, since x=ii\sqrt{x} = i*i. With binary search, the idea is the same except that we begin our search within the bounds of [0, x], and eliminate the left or right half depending on whether the algorithm overestimated or underestimated the solution.

Below, when pow < x, we know this resulted in a underestimation so the next iteration will extend [mid+1, high].

Complexity: O(log(x)) time and O(log(x)) space

int mySqrt(int x)
{
    if (x == 0 || x == 1) return x;

    long long start = 1, end = x, mid, pow, ans;
    while (start <= end)
    {
        mid = (start + end) / 2;
        pow = mid*mid;

        if (pow == x) return mid;
        else if (pow < x) {
            start = mid + 1;
            ans = mid;
        }
        else end = mid - 1;

    }
    return ans;
}

int main()
{
    cout << mySqrt(2) << endl;
    cout << mySqrt(1) << endl;
    cout << mySqrt(2147483647) << endl;
}

Recursive Python Solution

Last updated

Was this helpful?