Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved integer square root. #202

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions contracts/libraries/Math.sol
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,29 @@ library Math {
z = x < y ? x : y;
}

// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
function sqrt(uint256 x) internal pure returns (uint256) {
unchecked {
if (x <= 1) { return x; }
if (x >= ((1 << 128) - 1)**2) { return (1 << 128) - 1; }
uint256 xAux = x;
uint256 result = 1;
if (xAux >= (1 << 128)) { xAux >>= 128; result = 1 << 64; }
if (xAux >= (1 << 64 )) { xAux >>= 64; result <<= 32; }
if (xAux >= (1 << 32 )) { xAux >>= 32; result <<= 16; }
if (xAux >= (1 << 16 )) { xAux >>= 16; result <<= 8; }
if (xAux >= (1 << 8 )) { xAux >>= 8; result <<= 4; }
if (xAux >= (1 << 4 )) { xAux >>= 4; result <<= 2; }
if (xAux >= (1 << 2 )) { result <<= 1; }
result = (3 * result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
if (result * result <= a) {
return result;
}
return result-1;
}
}