Skip to content

Commit 94fb442

Browse files
onybhwwhww
authored andcommitted
Implement fast integer square root
1 parent caf0869 commit 94fb442

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

eth/_utils/numeric.py

Lines changed: 7 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,7 @@ 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``.
108108
"""
109109
if not isinstance(value, int) or isinstance(value, bool):
110110
raise ValueError(
@@ -119,9 +119,8 @@ def integer_squareroot(value: int) -> int:
119119
)
120120
)
121121

122-
x = value
123-
y = (x + 1) // 2
124-
while y < x:
125-
x = y
126-
y = (x + value // x) // 2
127-
return x
122+
with decimal.localcontext() as ctx:
123+
# Set precision to 128, since the largest square root of a
124+
# 256-bit integer is a 128-bit integer.
125+
ctx.prec = 128
126+
return int(decimal.Decimal(value).sqrt())

0 commit comments

Comments
 (0)