我正在尝试实现本文Faster Sieve of Eratosthenes中描述的算法。我很了解这个主意,但是我无法把握如何通过python代码实现它。
经过一些工作,我找到了一种将筛子的索引转换为数字本身的方法:
number = lambda i: 3 * (i + 2) - 1 - (i + 2) % 2
但是主要的问题是我在获得质素后必须做的跳动作。文章将其解释为:
6np±p,其中p是素数,n是一些自然数。
是否有一种方法可以使用这种想法的最后找到的质数来描述跳跃?
谢谢。
P.S。 有implementation in Objective-C 我对编程很陌生,只能理解python和js代码。
答案 0 :(得分:0)
如果您既了解numpy又了解Python,请查看this answer in StackOverflow中的primesfrom2to
的实现。
def primesfrom2to(n):
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a array of primes, 2 <= p < n """
sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k] = False
sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False
return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]
在我链接的答案中,此例程是建立素数列表最快的例程。我在探索素数的代码中使用了它的变体。对此进行详细解释会占用很多空间,但是它会构建一个sieve
,其中省略了2和3的倍数。仅两行代码(以sieve[
开始和以= False
结尾的代码)标出新发现的素数的倍数。我认为这就是您所说的“在获得质素后跳...”的意思。该代码很棘手,但正在研究中。该代码适用于Python 2,旧版Python。
这是我自己的一些带有更多注释的Python 3代码。您可以使用它进行比较。
def primesieve3rd(n):
"""Return 'a third of a prime sieve' for values less than n that
are in the form 6k-1 or 6k+1.
RETURN: A numpy boolean array. A True value means the associated
number is prime; False means 1 or composite.
NOTES: 1. If j is in that form then the index for its primality
test is j // 3.
2. The numbers 2 and 3 are not handled in the sieve.
3. This code is based on primesfrom2to in
<https://stackoverflow.com/questions/2068372/
fastest-way-to-list-all-primes-below-n-in-python/
3035188#3035188>
"""
if n <= 1: # values returning an empty array
return np.ones(0, dtype=np.bool_)
sieve = np.ones(n // 3 + (n % 6 == 2), dtype=np.bool_) # all True
sieve[0] = False # note 1 is not prime
for i in range(1, (math.ceil(math.sqrt(n)) + 1) // 3): # sometimes large
if sieve[i]:
k = 3 * i + 1 | 1 # the associated number for this cell
# Mark some of the stored multiples of the number as composite
sieve[k * k // 3 :: 2 * k] = False
# Mark the remaining stored multiples (k times next possible prime)
sieve[k * (k + 4 - 2*(i&1)) // 3 :: 2 * k] = False
return sieve
def primesfrom2to(n, sieve=None):
"""Return an array of prime numbers less than n.
RETURN: A numpty int64 (indices type) array.
NOTES: 1. This code is based on primesfrom2to in
<https://stackoverflow.com/questions/2068372/
fastest-way-to-list-all-primes-below-n-in-python/
3035188#3035188>
"""
if n <= 5:
return np.array([2, 3], dtype=np.intp)[:max(n - 2, 0)]
if sieve is None:
sieve = primesieve3rd(n)
elif n >= 3 * len(sieve) + 1 | 1: # the next number to note in the sieve
raise ValueError('Number out of range of the sieve in '
'primesfrom2to')
return np.r_[2, 3, 3 * np.nonzero(sieve)[0] + 1 | 1]
问我这里是否有您不理解的东西。