<p>我写了下面的代码,它应该检查输入的数字是否是质数,但有一个问题我无法解决:</p>
<pre><code>def main():
n = input("Please enter a number:")
is_prime(n)
def is_prime(a):
x = True
for i in (2, a):
while x:
if a%i == 0:
x = False
else:
x = True
if x:
print "prime"
else:
print "not prime"
main()
</code></pre>
<p>如果输入的数字不是质数,它会显示“非质数”,这是应该的,但如果数字是质数,它不会显示任何内容。你能帮我一下吗?</p>
<p>测试素性有很多有效的方法(这不是其中之一),但是您编写的循环可以用Python简洁地重写:</p>
<pre><code>def is_prime(a):
return all(a % i for i in xrange(2, a))
</code></pre>
<p>也就是说,如果2和a(不包括2和a)之间的所有数字在除以a时都给出非零余数,则a为素数</p>