python - Python 因式分解函数的结果不稳定

标签 python factorization

def test_prime(n):
    q = True
    for p in range(2,n):  #Only need to check up to rootn for primes and n/2 for factors
        if int(n%p) is 0:         
            q = False
            print(p, 'and', int(n/p), 'are factors of ', n)    
    if q:
        print(n, 'IS a prime number!')
    else:
        print(n, 'IS NOT a prime number')

我刚刚开始使用 Python,我正在整理一些零碎的东西来打发时间。我一直在尝试测试素数,并有显示非素数因子的想法。我在上面放在一起的函数似乎运行良好,只是给出了不一致的输出。

例如如果我设置 n = 65432 我得到...

2 and 32716 are factors of  65432
4 and 16358 are factors of  65432
8 and 8179 are factors of  65432
8179 and 8 are factors of  65432
16358 and 4 are factors of  65432
32716 and 2 are factors of  65432
65432 IS NOT a prime number

这正是我所期望的。但是如果我设置 n = 659306 我会得到...

2 and 329653 are factors of  659306
71 and 9286 are factors of  659306
142 and 4643 are factors of  659306
4643 and 142 are factors of  659306
9286 and 71 are factors of  659306
659306 IS NOT a prime number

这是不同的,因为它在最后不包含因子 329653。这不是问题,因为所有因素都显示在某处,但令我恼火的是我不知道为什么某些数字会发生这种情况!

只是为了向您表明我不是一个彻头彻尾的白痴,我发现这似乎只发生在长度超过 5 个字符的整数值上。有人可以告诉我为什么这两种情况下的输出不同吗?

最佳答案

你想要 n % p == 0,而不是 n % p is 0is 测试同一性,而不是相等性,并且并非每个 0 都与其他 0 相同。

>>> 659306 % 329653
0
>>> (659306 % 329653) == 0
True
>>> (659306 % 329653) is 0
False
>>> id(0)
136748976
>>> id(659306 % 329653) 
3070888160

那里的id基本上对应了内存中的一个位置。

这样想:如果你有一个加元,我有一个加元,那么它们的值(value)就相等 (1 == 1),但它们不是同一个对象(我的一美元硬币与您的一美元硬币不同。)我们可以共享相同的硬币,但我们没有必要这样做。

[PS:您可以使用 n//p 代替 int(n/p) 进行整数除法。]

关于python - Python 因式分解函数的结果不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592649/

相关文章:

python - PyQt - 如何让我的文本上有星号?

algorithm - 查找范围内的自身产品的数量

java - 确定b是否是a的因子的有效方法?

python - to_excel() read_excel() 出现 Pandas Unicode 导入导出错误

python - 如何调整字符串x轴的 'tick frequency'

Java BigInteger分解: division and multiplication differ

C语言中的乔列斯基因式分解?

optimization - 优化 Julia 中的除数算法?

Python散点图二维数组

python - Flask + SQLAlchemy - 修改列 setter 的自定义元类(动态 hybrid_property)