程序如下:用户输入x个值,这些值将存储到列表中。然后程序遍历列表中的每个数字,并确定它是否为素数。
我一直想弄清楚我是怎么做到的,但是,现在我真的很困惑,程序不起作用。如何修复程序以使其实际工作?
这是我到目前为止所得到的:
print("Hello User, this is the Prime Numbers Game!")
print("You will be required to input 5 numbers, and the game will return which numbers are prime, and which numbers aren't")
new_list = []
counter = 0
counter1 = 0
while counter < 5:
new_list.append(int(input()))
counter += 1
index = 0
for index in range(0, int(enumerate(new_list, start = 1)):
for i in range(2, new_list[index]):
if new_list[index] % i != 0:
print(str(new_list[index]) + " IS PRIME")
elif new_list[index] < 2:
print(str(new_list[index]) + " IS PRIME")
elif new_list[index] % i == 0:
print(str(new_list[index]) + " IS NOT PRIME")
答案 0 :(得分:0)
所以有几件事可以帮助你。
首先,你在for循环线上缺少一个右括号。
其次,在这种情况下使用枚举是没有必要的,因为您不必担心使用值和索引。只需使用for循环即可!有关枚举(http://book.pythontips.com/en/latest/enumerate.html)
的更多信息,请查看此链接第三,内部for循环中的逻辑略微偏离。仅仅因为一个数字没有除以当前被检查的数字,它并不意味着它是素数。它不能除以2和n-1之间的 ALL 数字(换句话说,只能除以1和它本身)。
我在代码中做了一些更改,以反映我上面的陈述。
print("Hello User, this is the Prime Numbers Game!")
print("You will be required to input 5 numbers, and the game will return which numbers are prime, and which numbers aren't")
new_list = []
counter = 0
counter1 = 0
while counter < 5:
new_list.append(int(input()))
counter += 1
index = 0
for index in range(0, len(new_list)):
isPrime = True
for i in range(2, new_list[index]):
if new_list[index] % i == 0:
isPrime = False
break
elif new_list[index] < 2:
break
if (isPrime):
print(str(new_list[index]) + " IS PRIME")
else:
print(str(new_list[index]) + " IS NOT PRIME")
答案 1 :(得分:0)
以下是我的解决方案。它也适用于数字1和1。 2这是您使用的逻辑中的特殊情况:
print("Hello User, this is the Prime Numbers Game!")
print("You will be required to input 5 numbers, and the game will return which numbers are prime, and which numbers aren't")
new_list = []
counter = 0
counter1 = 0
while counter < 5:
new_list.append(int(input()))
counter += 1
print(new_list)
for index in range(0, len(new_list)):
if new_list[index] <= 2:
if new_list[index] == 1:
print(str(new_list[index]) + " IS NOT A PRIME")
else:
print(str(new_list[index]) + " IS A PRIME")
continue
for counter in range(2, new_list[index]):
if new_list[index] % counter == 0:
print(str(new_list[index]) + " IS NOT A PRIME")
break
if counter==new_list[index] -1: #this means you have gone through all numbers and found nothing dividable
print(str(new_list[index])+ " IS A PRIME")