Last active
October 17, 2022 20:44
-
-
Save orhanobut/9267654 to your computer and use it in GitHub Desktop.
how to find square root of an integer with binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
This code is not properly updating the values. Will stuck in infinite loop. e.g. for a = 2.