Algo-Sim › Binary Search

Sqrt(x)

Easy · Binary Search · step through it in Java, Python and C++ on your own input

Binary search on the answer: the largest m with m · m ≤ x, testing mid ≤ x / mid so the square never overflows.

Problem

Given a non-negative integer x, return its square root rounded down to an integer, without using a built-in power or square-root function.

Constraints

Edge cases to test

Follow-up questions

How do you avoid overflow?
Compare mid ≤ x / mid or use 64-bit products.
Is there a faster method?
Newton’s method r = (r + x / r) / 2 converges quadratically: O(log log x) iterations in practice.
What if you need decimals?
Binary search on doubles for a fixed number of iterations (or until hi − lo < ε): about 60 rounds for full double precision.

Solution

Java

public int mySqrt(int x) {
    if (x < 2) return x;
    int lo = 1, hi = x / 2, ans = 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (mid <= x / mid) {
            ans = mid;
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }
    return ans;
}

Python

def my_sqrt(x):
    if x < 2: return x
    lo, hi, ans = 1, x // 2, 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if mid <= x // mid:
            ans = mid
            lo = mid + 1
        else:
            hi = mid - 1
    return ans

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int mySqrt(int x) {
        if (x < 2) return x;
        int lo = 1, hi = x / 2, ans = 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (mid <= x / mid) {
                ans = mid;
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return ans;
    }
};

More Binary Search problems