Python 3.x loopinbg问题-尝试从列表中查找素数
我得到一个数字列表,使用python,我需要在列表中找到素数并打印出来 我试过几种不同的方法,但都不能完全奏效。我的最新尝试如下,但它只是返回所有数字,并显示消息,说明它是一个素数,但最后一个除外Python 3.x loopinbg问题-尝试从列表中查找素数,python-3.x,Python 3.x,我得到一个数字列表,使用python,我需要在列表中找到素数并打印出来 我试过几种不同的方法,但都不能完全奏效。我的最新尝试如下,但它只是返回所有数字,并显示消息,说明它是一个素数,但最后一个除外 odd_numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29] x = 0 y = len(odd_numbers) - 1 # If given number is greater t
odd_numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
x = 0
y = len(odd_numbers) - 1
# If given number is greater than 1
#if odd_numbers[x] > 2:
# Iterate from 2 to n / 2
for i in range(0, y):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (odd_numbers[x] % 2) == 0:
break
else:
pr_no = odd_numbers[x]
print(odd_numbers[x], "is a prime number")
x = x + 1
else:
print(odd_numbers[x], "is not a prime number")
它应该做的是打印出:
2是质数
3是列表中所有素数的素数等我的回答对你有帮助吗?
odd_numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
for x in odd_numbers:
if x > 1:
for y in range(2,x):
if (x % y) == 0:
# print(x,"is not a prime number")
# print(y,"times",x//y,"is",x)
break
else:
print(y,"is a prime number")
# else:
# print(x, "is not a prime number")