Skip to content

Instantly share code, notes, and snippets.

@orhanobut
Last active October 17, 2022 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orhanobut/9267654 to your computer and use it in GitHub Desktop.
Save orhanobut/9267654 to your computer and use it in GitHub Desktop.
how to find square root of an integer with binary search
public static int sqr(int a){
if (a < 1) return 0;
int low = 1;
int h = a;
while (low < h){
int m = low + (h - low) / 2;
int s = m * m;
if (s == a){
return m;
} else if (s < a){
low = m;
} else {
h = m;
}
}
return 0;
}
@rauf
Copy link

rauf commented Jun 23, 2019

This code is not properly updating the values. Will stuck in infinite loop. e.g. for a = 2.

@a1k0u
Copy link

a1k0u commented Oct 17, 2022

This is the brilliant code in C++. For all n from 0 to 2^64 - 1.

#include <iostream>

unsigned long long binary_sqrt(uint64_t n) {
    __int128 left = 0, right = n, middle;

    if (n == 0) return 0;

    while (right - left > 1) {
        middle = (right + left) / 2;

        if (middle * middle <= n)
            left = middle;
        else
            right = middle;
    }

    return left;
}

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    uint64_t n;

    while (std::cin >> n)
        std::cout << binary_sqrt(n) << "\n";

    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment