Python显示整数有多长?

标签 python python-2.7 long-integer

这里有两个用于查找数字素因数的函数。 学分:三联画 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)

哪里d2 开始(肯定是 int 无论哪个运行时),通过 d = d + 1 增长(两个 int 相加)并且 - 当它作为一个因子附加时 - 位于 7197863 (仍然是 int )。

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

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

哪里n65126264424 开始并通过 n /= d 缩小。这不会改变 n 的类型如果它以 long 开头(如果 nlong 并且 dint ,则结果仍然是 long 无论多小)。因此,问题变成:65126264424一个long

答案取决于你的 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/

相关文章:

python - 替换文件中的字符串

c - 秒到纳秒 - struct itimerspec

python - matplotlib 上的常见 y 标签未调整

python - 编辑距 ionic 串

python - Pandas 发现两列之间的累积差异

带范围的 Python 列表

python - 使用 ** 运算符在 python 中求平方根

Python 2 pdb : a statement behaves differently when run at the pdb prompt

c++ - 长整数输出错误

java - 如何通过将它们转换为 long 来减去两次