为什么我的Erasthotenes筛不起作用?Python 3
这是我的密码。我试图做一个有效但简单的Erasthotenes筛选,但当我运行程序时,它只会不断返回整数,不管我把范围放多大。这是在Python3中实现的为什么我的Erasthotenes筛不起作用?Python 3,python,python-3.x,primes,Python,Python 3.x,Primes,这是我的密码。我试图做一个有效但简单的Erasthotenes筛选,但当我运行程序时,它只会不断返回整数,不管我把范围放多大。这是在Python3中实现的 lyst = [] for i in range(2, 100): print(i) lyst.append(i) count = 2 index = 1 for x in lyst: print(str(index) + " : " + str(count)) if x%count == 0 and x !=
lyst = []
for i in range(2, 100):
print(i)
lyst.append(i)
count = 2
index = 1
for x in lyst:
print(str(index) + " : " + str(count))
if x%count == 0 and x != count:
lyst.remove(x) #removing all multiples of count
if max(lyst) == count: #breaks loop if count is the largest prime
break
else:
count = lyst[lyst.index(count)+1] #turns count into next prime
index += 1 #this is just for me to track how many primes i've found
这应该可以。。。请查看删除倍数的内部循环:
lyst = []
max = 100 # because ... you know, variables. ...
for i in range(2, max):
lyst.append(i)
count = 2
index = 1
for x in lyst:
print(str(index) + " : " + str(x)) # x is a prime number, so print it
for y in lyst:
if y>x and y%x == 0:
lyst.remove(y)
index += 1 #this is just for me to track how many primes i've found
print(index) # how many did we find
这是您的代码和: x和count的值将始终具有相同的值:
- 他们一开始是这样的,值为2
- 因此,将不执行
删除
- 迭代结束时,count将是列表中的下一个值,这正是下一次迭代开始时x的值
if
条件
第二,Erasthotenes的筛子不应该去除筛子中的元素,而是将某些值标记为非素数。它的功能在于将值保持在原始索引,因此在普通筛选算法中不应该出现.remove()
要获得找到正确实现的灵感,您可以查看以下几个答案:
- 。。。还有更多
count==lyst…
?(并扔掉结果。)我正在尝试将计数转换为下一个素数,即列表中下一个最大的素数。试图复制维基百科上的筛子:你确实意识到你正在删除所有的x。。。不仅仅是倍数@对不起?我不明白我是怎么做到的。我想我加入了and运算符,那些只消除倍数的条件是比较,而不是赋值。你也没有做count==2
。Wikipedia的描述非常详细,一再重复乘法是以相等的增量生成的(即通过重复加法),而不是通过任何整除性测试得到的。@Willenss:非常好的评论,谢谢。修改现有脚本通常比从头开始更难。我更新了方法。很高兴能帮上忙。:)
n = 100
lyst = range(2, n)
for p in lyst:
if not p:
continue
for i in range(2*p,n,p):
lyst[i-2] = None
print [p for p in lyst if p]
#=> [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]