这段代码中怎么找素数,is_prime(9) 返回True? [英] How come in this code to find prime numbers, is_prime(9) returns True?
本文介绍了这段代码中怎么找素数,is_prime(9) 返回True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
if x % n == 0:
return False
else:
return True
print is_prime(9)
返回 True
而不是 False
.
我不太明白.
range (2,9)
包括这个列表:2,3,4,5,6,7,8
和9 % 3 == 0
,那么为什么我没有得到 False
作为该函数的答案?
and 9 % 3 == 0
,
So how come I do not get False
as the answer of that function?
推荐答案
这是因为您实际上并未循环,因为您在第一个循环中返回 True(9 % 2 == 0 为 False).
This is because you don't actually loop, as you return True during the first cycle (9 % 2 == 0 is False).
这样的事情应该可以解决问题:
Something like this should solve the problem:
def is_prime(x):
if x < 2:
return False
for n in range(2, x):
if x % n == 0:
return False
return True
这篇关于这段代码中怎么找素数,is_prime(9) 返回True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文