[英]How to print out numbers from a range generator that are not divisible by any numbers in a given list
I'm trying to print out prime numbers in a certain range and decided to go with the Segmented Sieve of Eratosthenes to find prime numbers from 2 up to sqrt(n) and use those found primes in the list to print out the prime numbers from any range such that a number in the range not divisible by any of the numbers in the sieve list ends up being a prime.我正在尝试打印出一定范围内的素数,并决定使用 Eratosthenes 的分段筛来 go 找到从 2 到 sqrt(n) 的素数,并使用列表中找到的素数打印出素数任何范围,使得范围内的数字不能被筛列表中的任何数字整除最终成为素数。
My code works for small ranges such as from 2 to 10 and 3 to 5 but starts printing out duplicates and also non-primes for large n.我的代码适用于小范围,例如从 2 到 10 和 3 到 5,但开始打印出重复项以及大 n 的非素数。 Any help fixing this?
有什么帮助解决这个问题吗?
from math import sqrt, ceil
#Creating segmented sieve
start=2
stop=1000000000
sieve=[i for i in range(2,ceil(sqrt(stop)+1))]
for num in range(0,len(sieve)):
num2=num+1
while num2<len(sieve):
if sieve[num2]%sieve[num]==0:
sieve.pop(num2)
num2+=1
else:
num2+=1
#printing primes from start to stop using primes in sieve to ignore their multiples
for n in range(start,stop+1):
if n==sieve[0]:
print(n)
continue
if n%sieve[0]==0:
continue
else:
p=1
while p<len(sieve):
if n==sieve[p]:
print(n)
p+=1
continue
if n%sieve[p]==0:
p+=1
continue
else:
p+=1
print(n)
The problem was in the while loop.问题出在while循环中。 If one of the conditions in the loop is met, it means that you found a prime number so you should "break" out of the loop instead of printing it and continuing.
如果满足循环中的条件之一,则意味着您找到了一个素数,因此您应该“中断”循环而不是打印并继续。 And, to ensure that the number is checked by all numbers in the sieve list, a final conditional set so that it only breaks if the other conditions aren't met and it has reached the end of the sieve list.
并且,为了确保筛选列表中的所有数字都检查该数字,一个最终条件集,以便仅在不满足其他条件并且已到达筛选列表末尾时才中断。
while p < len(sieve):
if n == sieve[p]:
print(n)
break
if n % sieve[p] == 0:
break
if p == (len(sieve)-1):
print(n)
break
else:
p += 1
Output: Output:
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.