[英]Incorrect Prime number list in python
I had assumed my Python prime number list was good. 我以为我的Python素数列表很好。 But it's printing out numbers the moment it sees that it is not divisible by 2. I've tried to iterate loops through the list that contains other prime numbers such as 3, 5, 7 ... but it does not seem to work still.
但是,它在看到它不能被2整除的那一刻就打印出数字。我试图遍历包含其他质数(例如3、5、7)的列表中的循环,但是它似乎仍然无法正常工作。
primes = []
input = raw_input("> ")
input2 = raw_input("> ")
for num in range(int(input), int(input2)):
for j in primes:
if not primes:
break
else:
if j % num ==0:
break
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
break
print primes
This prints out numbers divisible by 3 but not divisible by 2. 打印出可被3整除但不能被2整除的数字。
for num in range(int(input), int(input2)):
if not primes:
break
else:
for j in primes:
if j % num ==0:
break
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
break
print primes
This code is printing out an empty list. 此代码正在打印一个空列表。 It made sense to me logically but the code is not executing the way I expect it to.
从逻辑上来说,这对我来说很有意义,但是代码并未按照我期望的方式执行。 What is wrong here???
这是怎么了???
Your first for loop isnt doing anything useful: 您的第一个for循环不会做任何有用的事情:
for num in range(int(input), int(input2)):
for j in primes: #there is nothing in list 'primes'
if not primes: #this won't execute
break #this won't execute
else: #this will execute
if j % num ==0: #this will execute
break #break if statement, repeat for loop
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
break
print primes
With that said, this would be the most convenient way to get your desired output: 话虽如此,这将是获得所需输出的最便捷方法:
primes=[]
input = raw_input("> ")
input2 = raw_input("> ")
for num in range(int(input), int(input2)):
if all(num%i!=0 for i in range(2,num)):
primes.append(num)
print primes
your second "else" seems to be in the wrong place. 您的第二个“其他”似乎在错误的位置。 try this modified version of your program :
试试这个程序的修改版本:
primes = []
input = raw_input("> ")
input2 = raw_input("> ")
for num in range(int(input), int(input2)+1):
# prime numbers are greater than 1
if num > 1 :
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
print primes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.