Skip to content

Instantly share code, notes, and snippets.

@HirbodBehnam
Last active November 6, 2020 13:07
Show Gist options
  • Select an option

  • Save HirbodBehnam/ec8f02f73608fe4aaa94d6d27bcb4bbe to your computer and use it in GitHub Desktop.

Select an option

Save HirbodBehnam/ec8f02f73608fe4aaa94d6d27bcb4bbe to your computer and use it in GitHub Desktop.
A simple script to calculate the floor(sqrt(x)) with binary search in cpp. Also prevents the integer overflow on large values.
unsigned long long floor_sqrt(unsigned long long x)
{
unsigned long long low = 0, high = x;
// prevent integer overflow on pow2
if (high > 18446744065119617025)
return 4294967296;
if (high > 4294967296 * 2 - 1)
high = 4294967296 * 2 - 1;
// use binary search
while(low <= high)
{
const auto mid = (low + high) / 2;
const auto pow2 = mid * mid;
if (pow2 == x)
return mid;
if (pow2 < x) // target must be higher
low = mid + 1;
else // target must be lower
high = mid - 1;
}
return high; // this returns the floor of the sqrt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment