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 个字符的整数值上。有人可以告诉我为什么这两种情况下的输出不同吗?