Skip to content

Commit b6da0b4

Browse files
authored
Merge pull request #1698 from onyb/fast-integer-squareroot
Implement fast integer square root
2 parents caf0869 + 4224a1a commit b6da0b4

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

eth/_utils/numeric.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import decimal
12
import functools
23
import itertools
34
from typing import (
@@ -103,8 +104,11 @@ def clamp(inclusive_lower_bound: int,
103104

104105
def integer_squareroot(value: int) -> int:
105106
"""
106-
Return the largest integer ``x`` such that ``x**2 <= value``.
107-
Ref: https://en.wikipedia.org/wiki/Integer_square_root
107+
Return the integer square root of ``value``.
108+
109+
Uses Python's decimal module to compute the square root of ``value`` with
110+
a precision of 128-bits. The value 128 is chosen since the largest square
111+
root of a 256-bit integer is a 128-bit integer.
108112
"""
109113
if not isinstance(value, int) or isinstance(value, bool):
110114
raise ValueError(
@@ -119,9 +123,6 @@ def integer_squareroot(value: int) -> int:
119123
)
120124
)
121125

122-
x = value
123-
y = (x + 1) // 2
124-
while y < x:
125-
x = y
126-
y = (x + value // x) // 2
127-
return x
126+
with decimal.localcontext() as ctx:
127+
ctx.prec = 128
128+
return int(decimal.Decimal(value).sqrt())

0 commit comments

Comments
 (0)