Skip to content

Instantly share code, notes, and snippets.

@henninglive
Created April 21, 2018 18:07
Show Gist options
  • Select an option

  • Save henninglive/32ca9b9d75a844085f5d43faa157b208 to your computer and use it in GitHub Desktop.

Select an option

Save henninglive/32ca9b9d75a844085f5d43faa157b208 to your computer and use it in GitHub Desktop.
Integer Square Root
/// Integer Square Root
///
/// `n` is the positive integer for which the return value is the greatest
/// integer less than or equal to the square root of n.
pub fn isqrt(mut n: usize) -> usize {
let mut res = 0;
let mut b = 1 << ((::std::mem::size_of::<usize>() * 8) - 2);
while b > n {
b >>= 2
}
while b != 0 {
if n >= res + b {
n -= res + b;
res = (res >> 1) + b;
}
else {
res >>= 1;
}
b >>= 2;
}
res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment