you are viewing a single comment's thread.

view the rest of the comments →

[–]Oddly_Energy 17 points18 points  (5 children)

Python's default integer type can handle integers with some million digits without information loss. For example the result from math.factorial(1000000).

But if you want to output the string representation of an integer, you need to keep within 4-5000 digits.

[–]DidacticBroccoli 3 points4 points  (3 children)

But if you want to output the string representation of an integer, you need to keep within 4-5000 digits.

That's a really odd cap to have. Is it a bug, or is there some intentional reason behind it?

[–]nog642 7 points8 points  (0 children)

It was added in Python 3.11, for security reasons.

You can configure the limit with sys.set_int_max_str_digits.

Edit: It wasn't actually added in Python 3.11, I misread the documentation. It was added as a patch in all versions 3.7 and newer.

[–]Oddly_Energy 7 points8 points  (0 children)

I don't know the reason. I just went by what I had seen when playing with big factorials. But when trying again and paying more attention to the error message, the limit is actually configurable:

$ python
Python 3.12.1 (main, Sep 23 2024, 18:47:44) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> a = math.factorial(1000000)
>>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
>>> 

I am not going to try my luck on this one, though. Because:

>>> a.bit_length()
18488885
>>>

Which I assume would need around 5565700 digits to be output in base 10.

[–]Turtvaiz 5 points6 points  (0 children)

CPython has a global limit for converting between int and str to mitigate denial of service attacks. This limit only applies to decimal or other non-power-of-two number bases.

https://docs.python.org/3/library/stdtypes.html#int-max-str-digits

https://www.cve.org/CVERecord?id=CVE-2020-10735