Created
April 21, 2018 18:07
-
-
Save henninglive/32ca9b9d75a844085f5d43faa157b208 to your computer and use it in GitHub Desktop.
Integer Square Root
This file contains hidden or 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
| /// 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