lazy computing of primes with python without recursion error

47 Views Asked by At

I came across this great video from computerphile which talked about lazy computing. In the video, they lay out this really beautiful bit of python code that will calculate primes using the sieve method "lazily"

def nats(n):
    yield n
    yield from nats(n+1)
def sieve(s): 
    n = next(s)
    yield n
    yield from sieve(i for i in s if i%n!=0)

The issue comes when you actually implement the code to calculate a large number of primes. Because you are recursively searching, the recursion depth is reached relatively quickly. I can only calculate a prime up to 2281

If I modify the code to get rid of recursion with the first function:

def nats(n):
    while True:
        yield n
        n += 1

Then I can get to prime 12379 before the recursion depth is reached.

If I understand the code correctly, you need recursion to keep inputting only digits that are prime candidates (via the sieve method) into the sieve function.

Is there a way to implement this "lazy computation" algorithm to do lazy computing without using recursion and thus calculating primes infinitely without running into recursion limit roadblocks?

0

There are 0 best solutions below