python-codewars-solutions/prime_streaming/stream.py

58 lines
1.2 KiB
Python
Raw Permalink Normal View History

2024-01-23 13:32:21 +00:00
import numpy as np
2024-03-06 15:06:02 +00:00
2024-01-23 13:32:21 +00:00
def sieve_np(limit):
if limit < 2:
return []
# Create a boolean array "is_prime" and initialize all entries as True
is_prime = np.ones(limit + 1, dtype=bool)
is_prime[0:2] = False # 0 and 1 are not prime numbers
for p in range(2, int(limit**0.5) + 1):
if is_prime[p]:
# Use array slicing to mark all multiples of p as not prime
is_prime[p**2 : limit + 1 : p] = False
# Create a list of prime numbers using NumPy's where function
primes = np.where(is_prime)[0]
return primes.tolist()
2024-03-06 15:06:02 +00:00
2024-01-23 13:32:21 +00:00
def sieve(max_n):
s = [True] * (max_n + 1)
p = 2
while p**2 <= max_n:
if s[p]:
for i in range(p**2, max_n + 1, p):
s[i] = False
p += 1
2024-03-06 15:06:02 +00:00
2024-01-23 13:32:21 +00:00
primes = [p for p in range(2, max_n + 1) if s[p]]
return primes
2024-03-06 15:06:02 +00:00
def sieve(max_n):
s = [True] * (max_n + 1)
2024-01-23 13:32:21 +00:00
p = 2
2024-03-06 15:06:02 +00:00
while p**2 <= max_n:
if s[p]:
for i in range(p**2, max_n + 1, p):
s[i] = False
2024-01-23 13:32:21 +00:00
p += 1
2024-03-06 15:06:02 +00:00
primes = [p for p in range(2, max_n + 1) if s[p]]
2024-01-23 13:32:21 +00:00
return primes
2024-03-06 15:06:02 +00:00
_primes = sieve(25_000_000)
2024-01-23 13:32:21 +00:00
class Primes:
2024-03-06 15:06:02 +00:00
global _primes
primes = _primes
2024-01-23 13:32:21 +00:00
@staticmethod
def stream():
yield from Primes.primes