Skip to content

Instantly share code, notes, and snippets.

@anthonyclays
Created September 14, 2015 08:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonyclays/6c10d17a9caf8767059b to your computer and use it in GitHub Desktop.
Save anthonyclays/6c10d17a9caf8767059b to your computer and use it in GitHub Desktop.
Fast perfect square test in Rust
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