File tree Expand file tree Collapse file tree 1 file changed +9
-8
lines changed Expand file tree Collapse file tree 1 file changed +9
-8
lines changed Original file line number Diff line number Diff line change
1
+ import decimal
1
2
import functools
2
3
import itertools
3
4
from typing import (
@@ -103,8 +104,11 @@ def clamp(inclusive_lower_bound: int,
103
104
104
105
def integer_squareroot (value : int ) -> int :
105
106
"""
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.
108
112
"""
109
113
if not isinstance (value , int ) or isinstance (value , bool ):
110
114
raise ValueError (
@@ -119,9 +123,6 @@ def integer_squareroot(value: int) -> int:
119
123
)
120
124
)
121
125
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 ())
You can’t perform that action at this time.
0 commit comments