GetPrimes code snippet:
def GetPrimes(n):
"""
Get all primes up to n.
Use sieve of Eratosthenes to generate all primes less or equal to n. For
example, given n = 10, then returns a list of primes [2, 3, 5, 7].
Args:
n: An integer representing the upper bound.
Returns:
A list containing all primes <= n in the increasing order.
"""
sqrt_n = int(math.sqrt(n))
visited = [False] * (n + 1)
for i in range(2, sqrt_n + 1):
if not visited[i]:
for j in range(i * i, n + 1, i):
visited[j] = True
primes = []
for i in range(2, n + 1):
if not visited[i]:
primes.append(i)
return primes
沒有留言:
張貼留言