Python- Sieve of Eratosthenes- Compact Python

后端 未结 8 1272
醉话见心
醉话见心 2021-01-06 14:09

This is my code for finding primes using the Sieve of Eratosthenes.

list = [i for i in range(2, int(raw_input(\"Compute primes up to what number? \"))+1)]  
         


        
8条回答
  •  無奈伤痛
    2021-01-06 14:16

    Here's a simple demonstration of the sieve. Note that lambda isn't used as the filtering function, because the prime number needs to bound at definition time. Also of interest is that it's efficient in the sense of not duplicating divisions, but in the long run it could lead to you-know-what.

    import itertools
    
    def primes():
        ints = itertools.count(2)
        while True:
            p = next(ints)
            yield p
            ints = itertools.ifilter(p.__rmod__, ints)
    
    print list(itertools.islice(primes(), 10))
    # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    

提交回复
热议问题