Fastest-in term of space- way to find prime numbers with python

后端 未结 4 1518
温柔的废话
温柔的废话 2020-11-30 13:21

Maybe it is a stupid question, but i was wondering if you could provide the shortest source to find prime numbers with Python. I was also wondering how to find prime numbers

4条回答
  •  日久生厌
    2020-11-30 14:13

    This uses more characters, but it's readable:

    def primes_to(n):
        cands = set(xrange(2, n))
        for i in xrange(2, int(n ** 0.5) + 1):
            for ix in xrange(i ** 2, n, i):
                cands.discard(ix)
        return list(cands) 
    

    EDIT

    A new way, similar to the above, but with less missed attempts at discard:

    def primes_to(n):
        cands = set(xrange(3, n, 2))
        for i in xrange(3, int(n ** 0.5) + 1, 2):
            for ix in xrange(i ** 2, n, i * 2):
                cands.discard(ix)
        return [2] + list(cands)
    

提交回复
热议问题