1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//! integer square root with binary search
pub fn isqrt(n: u64) -> u64 {
if n < 2 {
return n;
}
let mut ok = 0;
let mut ng = n.min(1 << 32);
while ng - ok > 1 {
let x = (ok + ng) >> 1;
if x * x <= n {
ok = x;
} else {
ng = x;
}
}
ok
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test() {
use crate::integer_square_root_linear_u64::isqrt as naive;
for i in 0..1000 {
assert_eq!(isqrt(i), naive(i));
}
let cases = vec![(std::u64::MAX, (1 << 32) - 1)];
for (n, ans) in cases {
assert_eq!(isqrt(n), ans);
}
}
}