python 中缓慢的 Big Int 输出
有没有办法提高 python 中“str(bigint)”和“print bigint”的性能?打印大整数值需要花费大量时间。我尝试使用以下递归技术:
def p(x,n):
if n < 10:
sys.stdout.write(str(x))
return
n >>= 1
l = 10**n
k = x/l
p(k,n)
p(x-k*l,n)
n = 位数, x = bigint
但在某些情况下,当子调用中的 x 具有前导零时,该方法会失败。有没有其他方法或者更快的方法。 (请不要建议使用任何外部模块或库)。
Is there anyway to improve performance of "str(bigint)" and "print bigint" in python ? Printing big integer values takes a lot of time. I tried to use the following recursive technique :
def p(x,n):
if n < 10:
sys.stdout.write(str(x))
return
n >>= 1
l = 10**n
k = x/l
p(k,n)
p(x-k*l,n)
n = number of digits,
x = bigint
But the method fails for certain cases where x in a sub call has leading zeros. Is there any alternative to it or any faster method. ( Please do not suggest using any external module or library ).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 Python 整数到字符串的转换的运行时间为 O(n^2),其中 n 是数字的长度。对于足够大的数量,速度会很慢。对于 1,000,001 位数字,str() 在我的计算机上大约需要 24 秒。
如果您确实需要将非常大的数字转换为字符串,那么递归算法是一个很好的方法。
以下版本的递归代码应该可以工作:
它自动估计输出中的位数。对于 1,000,001 位数字,速度大约快 4 倍。
如果您需要更快,您可能需要使用外部库。
Conversion from a Python integer to a string has a running of O(n^2) where n is the length of the number. For sufficiently large numbers, it will be slow. For a 1,000,001 digit number, str() takes approximately 24 seconds on my computer.
If you are really needing to convert very large numbers to a string, your recursive algorithm is a good approach.
The following version of your recursive code should work:
It automatically estimates the number of digits in the output. It is about 4x faster for a 1,000,001 digit number.
If you need to go faster, you'll probably need to use an external library.
对于交互式应用程序,内置的
print
和str
函数在眨眼间运行。但是,如果您将大整数打印到(例如标准输出),以便另一个进程可以(从标准输入)读取它们,并且您发现二进制到十进制的操作会影响整体性能,那么您可以查看< a href="https://stackoverflow.com/questions/4358285/is-there-a-faster-way-to-convert-an-任意-large-integer-to-a-big-endian-seque">是有一个将任意大整数转换为大端字节序列的更快方法? (尽管接受的答案建议 numpy,它是一个外部库,但还有其他建议)。
For interactive applications, the built-in
print
andstr
functions run in the blink of an eye.If however you are printing big integers to (standard output, say) so that they can be read (from standard input) by another process, and you are finding the binary-to-decimal operations impacting the overall performance, you can look at Is there a faster way to convert an arbitrary large integer to a big endian sequence of bytes? (although the accepted answer suggests numpy, which is an external library, though there are other suggestions).