Simple prime number generator in Python

前端 未结 26 2139
感情败类
感情败类 2020-11-22 07:16

Could someone please tell me what I\'m doing wrong with this code? It is just printing \'count\' anyway. I just want a very simple prime generator (nothing fancy).

26条回答
  •  没有蜡笔的小新
    2020-11-22 07:58

    Similar to user107745, but using 'all' instead of double negation (a little bit more readable, but I think same performance):

    import math
    [x for x in xrange(2,10000) if all(x%t for t in xrange(2,int(math.sqrt(x))+1))]
    

    Basically it iterates over the x in range of (2, 100) and picking only those that do not have mod == 0 for all t in range(2,x)

    Another way is probably just populating the prime numbers as we go:

    primes = set()
    def isPrime(x):
      if x in primes:
        return x
      for i in primes:
        if not x % i:
          return None
      else:
        primes.add(x)
        return x
    
    filter(isPrime, range(2,10000))
    

提交回复
热议问题