我正在尝试开发一个素数筛,在纸上我的算法在纸上非常有意义,但在平方根上方的素数中返回一个非常短的合数选择。
例如,在 10,000(其平方根为 100)的限制(找到所有素数)的情况下,它与素数混合的合数是 115、119、121 和 125(都非常接近(及以上!)100)。
请让我知道我的代码有什么问题,哪些部分需要修复/如何修复。
澄清:我担心它返回的复合(非素数),在我的素数测试中我哪里出错了,我该如何纠正它?
到目前为止,这是我的筛子:
def primes(limit):
# Just make an empty list where the primes go
prime = []
# This next for loop just adds all the numbers of the form 6n+/-1 to the list, as all primes are of this form
for i in range(1,limit / 6 + 1):
prime.append(6*i - 1)
prime.append(6*i + 1)
# If the limit is divisible by 6, the last number on the list is sometimes over the limit
if limit % 6 == 0 and prime[-1] > limit:
prime.remove(prime[-1])
# This next line just finds the place of the 'square root' of the limit, which is as high as it has to check for factors
squareroot = min(range(len(prime)), key=lambda i: abs(prime[i]-(limit**0.5))) + 1
# Removing composites BELOW the square root
for p in prime[:squareroot][:]:
for f in range(2, int(p ** 0.5) + 1):
if p % f == 0:
prime.remove(p)
break
# Removing composites ABOVE the square root
for f in prime[:squareroot][:]:
for p in prime[squareroot:]:
if p % f == 0:
prime.remove(p)
return [2, 3] + prime