这里有两个用于查找数字素因数的函数。 学分:三联画 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类型而不是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)
哪里d
从 2
开始(肯定是 int
无论哪个运行时),通过 d = d + 1
增长(两个 int
相加)并且 - 当它作为一个因子附加时 - 位于 7197863
(仍然是 int
)。
在 prime_factors2(65126264424)
但是,您在此处附加最后一个因素:
if d*d > n:
if n > 1: factors.append(n)
哪里n
从 65126264424
开始并通过 n /= d
缩小。这不会改变 n
的类型如果它以 long
开头(如果 n
是 long
并且 d
是 int
,则结果仍然是 long
无论多小)。因此,问题变成:是 65126264424
一个long
?
答案取决于你的 python 运行时:
- 在 32 位运行时中,您通常拥有的 32 位整数最大值为
(2**31 - 1)
或2147483647
小于65126264424
. - 在 64 位运行时中,您通常拥有的 64 位整数最大值为
(2**63 - 1)
或9223372036854775807
大于65126264424
.
查看 sys.maxint
的输出它应该小于 65126264424
.
关于Python显示整数有多长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503640/