gpt4 book ai didi

Python 显示整数一样长?

转载 作者:行者123 更新时间:2023-11-28 21:46:43 24 4
gpt4 key购买 nike

所以这里有两个函数可以求一个数的质因数。致谢:三联画 https://stackoverflow.com/a/412942/6211963

def prime_factors1(n):
"""Returns all the prime factors of a positive integer"""
factors = []
d = 2
while n > 1:
while n % d == 0:
factors.append(d)
n /= d
d = d + 1

return factors

def prime_factors2(n):
"""Returns all the prime factors of a positive integer"""
factors = []
d = 2
while n > 1:
while n % d == 0:
factors.append(d)
n /= d
d = d + 1
if d*d > n:
if n > 1: factors.append(n)
break
return factors

很明显第二个代码运行速度快了很多,但是为什么它输出的最大因子是long-type而不是int?

>>> prime_factors1(65126264424)
[2, 2, 2, 3, 13, 29, 7197863]

>>> prime_factors2(65126264424)
[2, 2, 2, 3, 13, 29, 7197863L]

最佳答案

区别如下。在 prime_factors1(n) 中,最后一个因子附加在此处:

while n > 1:
while n % d == 0:
factors.append(d)

其中 d2 开始(无论在哪个运行时,绝对是一个 int),通过 d = d + 1 增长(两个 int 的加法)并且 - 当它作为一个因素附加时 - 位于 7197863 (仍然是一个 int)。

但是,在 prime_factors2(65126264424) 中,您在此处附加了最后一个因子:

if d*d > n:
if n > 1: factors.append(n)

n65126264424 开始,通过 n/= d 缩小。如果 nlong 开头(如果 nlong 并且d 是一个 int,无论多小,结果仍然是一个 long。因此问题变成了:65126264424long 吗?

答案取决于你的 python 运行时:

  1. 在 32 位运行时,您通常有 32 位整数,最大值为 (2**31 - 1)2147483647,小于 65126264424.
  2. 在 64 位运行时,您通常有 64 位整数,最大值为 (2**63 - 1)9223372036854775807,大于 65126264424.

查看 sys.maxint 的输出,它应该小于 65126264424

关于Python 显示整数一样长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com