Skip to content

Commit 5146317

Browse files
committed
isqrt: cite source and rename variables to match original C code
1 parent c97ab23 commit 5146317

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

library/core/src/num/uint_macros.rs

+16-11
Original file line numberDiff line numberDiff line change
@@ -1998,21 +1998,26 @@ macro_rules! uint_impl {
19981998
return self;
19991999
}
20002000

2001-
let mut x = self;
2002-
let mut c = 0;
2003-
let mut d = 1 << (self.ilog2() & !1);
2004-
2005-
while d != 0 {
2006-
if x >= c + d {
2007-
x -= c + d;
2008-
c = (c >> 1) + d;
2001+
// The algorithm is based on the one presented in
2002+
// <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)>
2003+
// which cites as source the following C code:
2004+
// <https://web.archive.org/web/20120306040058/http://medialab.freaknet.org/martin/src/sqrt/sqrt.c>.
2005+
2006+
let mut op = self;
2007+
let mut res = 0;
2008+
let mut one = 1 << (self.ilog2() & !1);
2009+
2010+
while one != 0 {
2011+
if op >= res + one {
2012+
op -= res + one;
2013+
res = (res >> 1) + one;
20092014
} else {
2010-
c >>= 1;
2015+
res >>= 1;
20112016
}
2012-
d >>= 2;
2017+
one >>= 2;
20132018
}
20142019

2015-
c
2020+
res
20162021
}
20172022

20182023
/// Performs Euclidean division.

0 commit comments

Comments
 (0)