【发布时间】:2017-09-26 18:45:41
【问题描述】:
这是我的代码:
from time import sleep
n = 5
k = 2
found_factors = 0
while True:
kinn = n/k
if (n == k) and found_factors == 0:
print("Found prime:", n)
n += 1
k = 2
found_factors = 0
sleep(0.1)
continue
elif (n == k) and found_factors > 0:
n += 1
k = 2
found_factors = 0
continue
if isinstance(kinn, int) == True:
found_factors += 1
k += 1
该程序旨在查找从 5 开始的素数。但由于某种原因,它将每个数字都输出为素数!
为什么会这样?
【问题讨论】:
-
Python 2 还是 3?
5 / 2没有做你认为它在 python 2 中所做的事情 -
isinstance(kinn, int)不会测试您认为它测试的内容。如果你想要一个可分性测试,那就是if n % k == 0,测试余数。 -
如果你使用 Python 3,你可能想要
5 // 2 -
您是否尝试过在调试模式下单步执行代码以找出问题所在?