How to implement an efficient infinite generator of prime numbers in Python?

后端 未结 13 2233
醉酒成梦
醉酒成梦 2020-11-22 01:50

This is not a homework, I am just curious.

INFINITE is the key word here.

I wish to use it as for p in primes(). I believe that this is a built-

13条回答
  •  隐瞒了意图╮
    2020-11-22 02:26

    Another way to do it:

    import itertools
    def primeseq():
        prime = [2]
        num = 0
        yield 2
        for i in itertools.count(3, 2):
            is_prime = True
            for num in prime:
                if i % num == 0:
                    is_prime = False
                    break
                elif num ** 2 > i: 
                    break
            if is_prime:
                prime.append(i)
                yield i
    

提交回复
热议问题