Created
September 14, 2015 08:37
-
-
Save anthonyclays/6c10d17a9caf8767059b to your computer and use it in GitHub Desktop.
Fast perfect square test in Rust
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
fn isqrt(n: usize) -> usize { | |
n == 0 && return n; | |
let mut s = (n as f64).sqrt() as usize; | |
s = (s + n / s) >> 1; | |
if s * s > n { s - 1 } else { s } | |
} | |
fn perfect_sqrt(n: usize) -> isize { | |
match n & 0xf { | |
0 | 1 | 4 | 9 => { | |
let t = isqrt(n); | |
if t*t == n { t as isize } else { -1 } | |
}, | |
_ => -1, | |
} | |
} | |
fn main() { | |
for n in 0..200 { | |
println!("{}: {}", n, perfect_sqrt(n)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment