从此脚本获取错误的输出。
#!/usr/bin/python
numbers = [1,3,5,7,8,25]
def primes():
for i in numbers:
if i > 1:
if (i % 2) == 0:
print "not prime"
else :
print "prime"
print primes()
它说25是素数,任何想法为什么?
答案 0 :(得分:1)
您的程序正在检查数字是否为奇数,而不是它们是否为素数。 这是您想要的验证(来自this page)
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
答案 1 :(得分:1)
import math
numbers = [1,3,5,7,8,25]
def primes(n):
if n == 2:
return True
if n%2 == 0 or n <= 1:
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2):
if n%divisor == 0:
return False
return True
for i in numbers:
print i, '\t', primes(i)
答案 2 :(得分:0)
您的代码只会检查奇数或偶数。不是素数。