Skip to content

Int ⇔ str の相互変換時の桁上限

概要

桁数の大きい str を int 型に変換しようとした際に下記のようなエラーが発生することがある。

ValueError: Exceeds the limit (4300) for integer string conversion: value has 16394 digits

これは変換時の 桁数の上限 (4300 桁) を超えているために生じている。

ss = int("2" * 10**4)
print(ss)

"""
Traceback (most recent call last):
  File "C:\github\atcoder\arc\arc154\a\main.py", line 31, in <module>
    ss = int("2" * 10**4)
         ^^^^^^^^^^^^^^^^
ValueError: Exceeds the limit (4300) for integer string conversion: value has 10000 digits
"""

対応方法

sys モジュールの set_int_max_str_digits で上限の桁数を指定できる。
上限を取り外したい場合は 0 を指定する。

import sys
sys.set_int_max_str_digits(0)   

ss = int("2" * 10**4)
print(ss)  # ok

参考