I have the following code which generates all the primes numbers below n
def sieve(n):
# sieve of Erathosthenes to generate prime numbers
sieve = [True]*(n//2)
for i in range(3, int(sqrt(n))+1, 2):
if sieve[i//2]:
sieve[i*i//2::i] = [False]*((n-i*i-1)//(2*i)+1)
return (2,) + tuple(2*i + 1 for i in range(1, n//2) if sieve[i])
How can I amend the code to make use of caching? I.e. when sieve(n)
is ran it first checks to see if it’s been ran already. If it has, and the current n
is less than or equal to the cached m
, it just looks up the cached result and slices where it needs to. If the current n
is greater than the cached m
, it generates any additional primes and then overwrites the cache.
Is this doable?
Edit: I’m aware of the @cache
decorator from functools, but I don’t think this answers my question, as this just considers if n == m
or not; it doesn’t consider if n < m
or n > m
7