|
| 1 | +"""Python implementations of some algorithms for use by longobject.c. |
| 2 | +The goal is to provide asymptotically faster algorithms that can be |
| 3 | +used for operations on integers with many digits. In those cases, the |
| 4 | +performance overhead of the Python implementation is not significant |
| 5 | +since the asymptotic behavior is what dominates runtime. Functions |
| 6 | +provided by this module should be considered private and not part of any |
| 7 | +public API. |
| 8 | +
|
| 9 | +Note: for ease of maintainability, please prefer clear code and avoid |
| 10 | +"micro-optimizations". This module will only be imported and used for |
| 11 | +integers with a huge number of digits. Saving a few microseconds with |
| 12 | +tricky or non-obvious code is not worth it. For people looking for |
| 13 | +maximum performance, they should use something like gmpy2.""" |
| 14 | + |
| 15 | +import sys |
| 16 | +import re |
| 17 | +import decimal |
| 18 | + |
| 19 | +_DEBUG = False |
| 20 | + |
| 21 | + |
| 22 | +def int_to_decimal(n): |
| 23 | + """Asymptotically fast conversion of an 'int' to Decimal.""" |
| 24 | + |
| 25 | + # Function due to Tim Peters. See GH issue #90716 for details. |
| 26 | + # https://github.com/python/cpython/issues/90716 |
| 27 | + # |
| 28 | + # The implementation in longobject.c of base conversion algorithms |
| 29 | + # between power-of-2 and non-power-of-2 bases are quadratic time. |
| 30 | + # This function implements a divide-and-conquer algorithm that is |
| 31 | + # faster for large numbers. Builds an equal decimal.Decimal in a |
| 32 | + # "clever" recursive way. If we want a string representation, we |
| 33 | + # apply str to _that_. |
| 34 | + |
| 35 | + if _DEBUG: |
| 36 | + print('int_to_decimal', n.bit_length(), file=sys.stderr) |
| 37 | + |
| 38 | + D = decimal.Decimal |
| 39 | + D2 = D(2) |
| 40 | + |
| 41 | + BITLIM = 128 |
| 42 | + |
| 43 | + mem = {} |
| 44 | + |
| 45 | + def w2pow(w): |
| 46 | + """Return D(2)**w and store the result. Also possibly save some |
| 47 | + intermediate results. In context, these are likely to be reused |
| 48 | + across various levels of the conversion to Decimal.""" |
| 49 | + if (result := mem.get(w)) is None: |
| 50 | + if w <= BITLIM: |
| 51 | + result = D2**w |
| 52 | + elif w - 1 in mem: |
| 53 | + result = (t := mem[w - 1]) + t |
| 54 | + else: |
| 55 | + w2 = w >> 1 |
| 56 | + # If w happens to be odd, w-w2 is one larger then w2 |
| 57 | + # now. Recurse on the smaller first (w2), so that it's |
| 58 | + # in the cache and the larger (w-w2) can be handled by |
| 59 | + # the cheaper `w-1 in mem` branch instead. |
| 60 | + result = w2pow(w2) * w2pow(w - w2) |
| 61 | + mem[w] = result |
| 62 | + return result |
| 63 | + |
| 64 | + def inner(n, w): |
| 65 | + if w <= BITLIM: |
| 66 | + return D(n) |
| 67 | + w2 = w >> 1 |
| 68 | + hi = n >> w2 |
| 69 | + lo = n - (hi << w2) |
| 70 | + return inner(lo, w2) + inner(hi, w - w2) * w2pow(w2) |
| 71 | + |
| 72 | + with decimal.localcontext() as ctx: |
| 73 | + ctx.prec = decimal.MAX_PREC |
| 74 | + ctx.Emax = decimal.MAX_EMAX |
| 75 | + ctx.Emin = decimal.MIN_EMIN |
| 76 | + ctx.traps[decimal.Inexact] = 1 |
| 77 | + |
| 78 | + if n < 0: |
| 79 | + negate = True |
| 80 | + n = -n |
| 81 | + else: |
| 82 | + negate = False |
| 83 | + result = inner(n, n.bit_length()) |
| 84 | + if negate: |
| 85 | + result = -result |
| 86 | + return result |
| 87 | + |
| 88 | + |
| 89 | +def int_to_decimal_string(n): |
| 90 | + """Asymptotically fast conversion of an 'int' to a decimal string.""" |
| 91 | + return str(int_to_decimal(n)) |
| 92 | + |
| 93 | + |
| 94 | +def _str_to_int_inner(s): |
| 95 | + """Asymptotically fast conversion of a 'str' to an 'int'.""" |
| 96 | + |
| 97 | + # Function due to Bjorn Martinsson. See GH issue #90716 for details. |
| 98 | + # https://github.com/python/cpython/issues/90716 |
| 99 | + # |
| 100 | + # The implementation in longobject.c of base conversion algorithms |
| 101 | + # between power-of-2 and non-power-of-2 bases are quadratic time. |
| 102 | + # This function implements a divide-and-conquer algorithm making use |
| 103 | + # of Python's built in big int multiplication. Since Python uses the |
| 104 | + # Karatsuba algorithm for multiplication, the time complexity |
| 105 | + # of this function is O(len(s)**1.58). |
| 106 | + |
| 107 | + DIGLIM = 2048 |
| 108 | + |
| 109 | + mem = {} |
| 110 | + |
| 111 | + def w5pow(w): |
| 112 | + """Return 5**w and store the result. |
| 113 | + Also possibly save some intermediate results. In context, these |
| 114 | + are likely to be reused across various levels of the conversion |
| 115 | + to 'int'. |
| 116 | + """ |
| 117 | + if (result := mem.get(w)) is None: |
| 118 | + if w <= DIGLIM: |
| 119 | + result = 5**w |
| 120 | + elif w - 1 in mem: |
| 121 | + result = mem[w - 1] * 5 |
| 122 | + else: |
| 123 | + w2 = w >> 1 |
| 124 | + # If w happens to be odd, w-w2 is one larger then w2 |
| 125 | + # now. Recurse on the smaller first (w2), so that it's |
| 126 | + # in the cache and the larger (w-w2) can be handled by |
| 127 | + # the cheaper `w-1 in mem` branch instead. |
| 128 | + result = w5pow(w2) * w5pow(w - w2) |
| 129 | + mem[w] = result |
| 130 | + return result |
| 131 | + |
| 132 | + def inner(a, b): |
| 133 | + if b - a <= DIGLIM: |
| 134 | + return int(s[a:b]) |
| 135 | + mid = (a + b + 1) >> 1 |
| 136 | + return inner(mid, b) + ((inner(a, mid) * w5pow(b - mid)) << (b - mid)) |
| 137 | + |
| 138 | + return inner(0, len(s)) |
| 139 | + |
| 140 | + |
| 141 | +def int_from_string(s): |
| 142 | + """Asymptotically fast version of PyLong_FromString(), conversion |
| 143 | + of a string of decimal digits into an 'int'.""" |
| 144 | + if _DEBUG: |
| 145 | + print('int_from_string', len(s), file=sys.stderr) |
| 146 | + # PyLong_FromString() has already removed leading +/-, checked for invalid |
| 147 | + # use of underscore characters, checked that string consists of only digits |
| 148 | + # and underscores, and stripped leading whitespace. The input can still |
| 149 | + # contain underscores and have trailing whitespace. |
| 150 | + s = s.rstrip().replace('_', '') |
| 151 | + return _str_to_int_inner(s) |
| 152 | + |
| 153 | + |
| 154 | +def str_to_int(s): |
| 155 | + """Asymptotically fast version of decimal string to 'int' conversion.""" |
| 156 | + # FIXME: this doesn't support the full syntax that int() supports. |
| 157 | + m = re.match(r'\s*([+-]?)([0-9_]+)\s*', s) |
| 158 | + if not m: |
| 159 | + raise ValueError('invalid literal for int() with base 10') |
| 160 | + v = int_from_string(m.group(2)) |
| 161 | + if m.group(1) == '-': |
| 162 | + v = -v |
| 163 | + return v |
| 164 | + |
| 165 | + |
| 166 | +# Fast integer division, based on code from Mark Dickinson, fast_div.py |
| 167 | +# GH-47701. Additional refinements and optimizations by Bjorn Martinsson. The |
| 168 | +# algorithm is due to Burnikel and Ziegler, in their paper "Fast Recursive |
| 169 | +# Division". |
| 170 | + |
| 171 | +_DIV_LIMIT = 4000 |
| 172 | + |
| 173 | + |
| 174 | +def _div2n1n(a, b, n): |
| 175 | + """Divide a 2n-bit nonnegative integer a by an n-bit positive integer |
| 176 | + b, using a recursive divide-and-conquer algorithm. |
| 177 | +
|
| 178 | + Inputs: |
| 179 | + n is a positive integer |
| 180 | + b is a positive integer with exactly n bits |
| 181 | + a is a nonnegative integer such that a < 2**n * b |
| 182 | +
|
| 183 | + Output: |
| 184 | + (q, r) such that a = b*q+r and 0 <= r < b. |
| 185 | +
|
| 186 | + """ |
| 187 | + if a.bit_length() - n <= _DIV_LIMIT: |
| 188 | + return divmod(a, b) |
| 189 | + pad = n & 1 |
| 190 | + if pad: |
| 191 | + a <<= 1 |
| 192 | + b <<= 1 |
| 193 | + n += 1 |
| 194 | + half_n = n >> 1 |
| 195 | + mask = (1 << half_n) - 1 |
| 196 | + b1, b2 = b >> half_n, b & mask |
| 197 | + q1, r = _div3n2n(a >> n, (a >> half_n) & mask, b, b1, b2, half_n) |
| 198 | + q2, r = _div3n2n(r, a & mask, b, b1, b2, half_n) |
| 199 | + if pad: |
| 200 | + r >>= 1 |
| 201 | + return q1 << half_n | q2, r |
| 202 | + |
| 203 | + |
| 204 | +def _div3n2n(a12, a3, b, b1, b2, n): |
| 205 | + """Helper function for _div2n1n; not intended to be called directly.""" |
| 206 | + if a12 >> n == b1: |
| 207 | + q, r = (1 << n) - 1, a12 - (b1 << n) + b1 |
| 208 | + else: |
| 209 | + q, r = _div2n1n(a12, b1, n) |
| 210 | + r = (r << n | a3) - q * b2 |
| 211 | + while r < 0: |
| 212 | + q -= 1 |
| 213 | + r += b |
| 214 | + return q, r |
| 215 | + |
| 216 | + |
| 217 | +def _int2digits(a, n): |
| 218 | + """Decompose non-negative int a into base 2**n |
| 219 | +
|
| 220 | + Input: |
| 221 | + a is a non-negative integer |
| 222 | +
|
| 223 | + Output: |
| 224 | + List of the digits of a in base 2**n in little-endian order, |
| 225 | + meaning the most significant digit is last. The most |
| 226 | + significant digit is guaranteed to be non-zero. |
| 227 | + If a is 0 then the output is an empty list. |
| 228 | +
|
| 229 | + """ |
| 230 | + a_digits = [0] * ((a.bit_length() + n - 1) // n) |
| 231 | + |
| 232 | + def inner(x, L, R): |
| 233 | + if L + 1 == R: |
| 234 | + a_digits[L] = x |
| 235 | + return |
| 236 | + mid = (L + R) >> 1 |
| 237 | + shift = (mid - L) * n |
| 238 | + upper = x >> shift |
| 239 | + lower = x ^ (upper << shift) |
| 240 | + inner(lower, L, mid) |
| 241 | + inner(upper, mid, R) |
| 242 | + |
| 243 | + if a: |
| 244 | + inner(a, 0, len(a_digits)) |
| 245 | + return a_digits |
| 246 | + |
| 247 | + |
| 248 | +def _digits2int(digits, n): |
| 249 | + """Combine base-2**n digits into an int. This function is the |
| 250 | + inverse of `_int2digits`. For more details, see _int2digits. |
| 251 | + """ |
| 252 | + |
| 253 | + def inner(L, R): |
| 254 | + if L + 1 == R: |
| 255 | + return digits[L] |
| 256 | + mid = (L + R) >> 1 |
| 257 | + shift = (mid - L) * n |
| 258 | + return (inner(mid, R) << shift) + inner(L, mid) |
| 259 | + |
| 260 | + return inner(0, len(digits)) if digits else 0 |
| 261 | + |
| 262 | + |
| 263 | +def _divmod_pos(a, b): |
| 264 | + """Divide a non-negative integer a by a positive integer b, giving |
| 265 | + quotient and remainder.""" |
| 266 | + # Use grade-school algorithm in base 2**n, n = nbits(b) |
| 267 | + n = b.bit_length() |
| 268 | + a_digits = _int2digits(a, n) |
| 269 | + |
| 270 | + r = 0 |
| 271 | + q_digits = [] |
| 272 | + for a_digit in reversed(a_digits): |
| 273 | + q_digit, r = _div2n1n((r << n) + a_digit, b, n) |
| 274 | + q_digits.append(q_digit) |
| 275 | + q_digits.reverse() |
| 276 | + q = _digits2int(q_digits, n) |
| 277 | + return q, r |
| 278 | + |
| 279 | + |
| 280 | +def int_divmod(a, b): |
| 281 | + """Asymptotically fast replacement for divmod, for 'int'. |
| 282 | + Its time complexity is O(n**1.58), where n = #bits(a) + #bits(b). |
| 283 | + """ |
| 284 | + if _DEBUG: |
| 285 | + print('int_divmod', a.bit_length(), b.bit_length(), file=sys.stderr) |
| 286 | + if b == 0: |
| 287 | + raise ZeroDivisionError |
| 288 | + elif b < 0: |
| 289 | + q, r = int_divmod(-a, -b) |
| 290 | + return q, -r |
| 291 | + elif a < 0: |
| 292 | + q, r = int_divmod(~a, b) |
| 293 | + return ~q, b + ~r |
| 294 | + else: |
| 295 | + return _divmod_pos(a, b) |
0 commit comments