这是我认为您正在尝试做的事情:
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
,然后在 ranged_primes
中将其称为 sqrt(y)
功能。
从 10**6
到 10*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 显示的结果.
我是一名优秀的程序员,十分优秀!