# Integer square root algorithm

**URL:** <https://users.rust-lang.org/t/integer-square-root-algorithm/13529>\
**Category:** announcements\
**Created:** [October 23, 2017, 12:39pm UTC](https://users.rust-lang.org/t/integer-square-root-algorithm/13529 "2017-10-23T12:39:37Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![scottmcm](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/scottmcm/32/4286_2.png) [@scottmcm](https://users.rust-lang.org/u/scottmcm)\
**Post date:** [October 23, 2017, 6:41pm UTC](https://users.rust-lang.org/t/integer-square-root-algorithm/13529/5 "2017-10-23T18:41:23Z")

</div>

For a project that didn't need perfect precision, I made this, which is surprisingly close:

```rust
fn rough_isqrt(x: usize) -> usize {
    if x == 0 { return x }

    let n = std::mem::size_of::<usize>() as u32 * 8;
    let scale = n - x.leading_zeros();
    let half = scale/2;
    let guess = ( (x >> half) + (1 << half) )/2;
    guess
}

```

(The playground ASM has an unnecessary branch due to an LLVM bug, which could be worked around with [ctlz\_nonzero in std::intrinsics - Rust](https://doc.rust-lang.org/std/intrinsics/fn.ctlz_nonzero.html))

---

_[View the full topic](https://users.rust-lang.org/t/integer-square-root-algorithm/13529)._
