【发布时间】:2016-03-17 02:00:17
【问题描述】:
我正在尝试开发一个素数筛,在纸面上,我的算法在纸面上非常有意义,但会在平方根上方的素数中返回一个非常短的合数选择。
例如,在 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
【问题讨论】:
-
“缩进仅在第一行有问题”。选择第一行下面的所有行并单击
{}代码按钮比键入该句子要快。 -
我不明白你的实际问题:你是担心你得到超过 100 的值,还是担心你得到合数?
-
所有素数都不是
6n +/- 1的形式。 -
Peter wood -- 是的,至少是 2 和 3 以上的素数。这已经在数学上得到证明。至于 Evert,我担心我会得到复合数字(如 115、119 等)——但我得到的所有复合数字都正好高于极限的平方根(在本例中为 10,000)。我想知道为什么我会得到这些复合材料,以及如何才能停止得到它们。
-
但是您的素数列表不包括
2和3。