eratosthenes的分段筛:按指数筛选复合数?

时间:2014-08-06 09:58:29

标签: python python-3.x primes sieve-of-eratosthenes

我试图编写一个素数查找器,用于在两个给定值之间打印素数。我对编码传统筛子没有任何问题,但是当它被分割时,我的python知识就会缩短。这是我到目前为止所做的:

def primes(n): # traditional sieve finding primes up to sqrt(n)
    myPrimeList= []
    mySieve= array('B', [True]) * (int(n**0.5)+1)
    for i in range(2,int((n**0.5)+1)):
        if mySieve[i]:
            myPrimeList.append(i)
            for x in range(i*i,int(n**0.5)+1,i):
                mySieve[x]= False
    return myPrimeList

def rangedprimes(x,y):
    output = []
    sieve = [True] * (y-x+1)
    primeList = primes(y) # primes up to sqrt(y)
    minimums = [(x//m)*m for m in primeList if x>=m] # multiplying primes so they get close to the lower limit
    zipped = list(zip(primeList, minimums)) # just zipped to see it clearer, contributes nothing
    return zipped

print(primes(20))
print(rangedprimes(10,20))

[2, 3] # primes up to sqrt(20)
[(2, 10), (3, 9)] # primes and their smallest multiples

现在,根据算法,我必须转换这些数字' [10,12,14,15,16,18,20] 在筛子中从TrueFalse的值,以便剩余的数字,将标记为True ,可以是素数。在这一点上,我无法实现这一点,因为我的筛网只包含True y-x+1次,这意味着它的索引从0到{{ 1}}。例如, 16 20 如何在筛选中用y-x标记,其中最后一个索引号将仅 10 ?如果False的起始索引号是 10 ,而最后一个索引号是 20 ,我可以通过查看他们的筛子中找到数字索引并使它们成为sieve

在这种情况下筛子与复合数之间的关系应该是什么?

1 个答案:

答案 0 :(得分:3)

以下是我认为您正在尝试做的事情:

import math

def prime_sieve(n):
    """Use the Sieve of Eratosthenes to list primes 0 to n."""
    primes = range(n+1)
    primes[1] = 0
    for i in range(4, n+1, 2):
        primes[i] = 0
    for x in range(3, int(math.sqrt(n))+1, 2):
        if primes[x]:
            for i in range(2*primes[x], n+1, primes[x]):
                primes[i] = 0
    return filter(None, primes)

def ranged_primes(x, y):
    """List primes between x and y."""
    primes = prime_sieve(int(math.sqrt(y)))
    return [n for n in range(x, y) if all(n % p for p in primes)]

请注意,我已将传统筛子一直保留到n,然后在sqrt(y)函数中将其调用ranged_primes

10**610*6 + 10**3的演示:

>>> ranged_primes(10**6, 10**6+10**3)
[1000003, 1000033, 1000037, 1000039, 1000081, 
 1000099, 1000117, 1000121, 1000133, 1000151, 
 1000159, 1000171, 1000183, 1000187, 1000193, 
 1000199, 1000211, 1000213, 1000231, 1000249, ...]

匹配Wolfram Alpha显示的结果。