Simple prime number generator in Python

前端 未结 26 1778
感情败类
感情败类 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 08:11

    re is powerful:

    import re
    
    
    def isprime(n):
        return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None
    
    print [x for x in range(100) if isprime(x)]
    
    ###########Output#############
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    
    0 讨论(0)
  • 2020-11-22 08:11
    def genPrimes():
        primes = []   # primes generated so far
        last = 1      # last number tried
        while True:
            last += 1
            for p in primes:
                if last % p == 0:
                    break
            else:
                primes.append(last)
                yield last
    
    0 讨论(0)
  • 2020-11-22 08:12

    Here's a simple (Python 2.6.2) solution... which is in-line with the OP's original request (now six-months old); and should be a perfectly acceptable solution in any "programming 101" course... Hence this post.

    import math
    
    def isPrime(n):
        for i in range(2, int(math.sqrt(n)+1)):
            if n % i == 0: 
                return False;
        return n>1;
    
    print 2
    for n in range(3, 50):
        if isPrime(n):
            print n
    

    This simple "brute force" method is "fast enough" for numbers upto about about 16,000 on modern PC's (took about 8 seconds on my 2GHz box).

    Obviously, this could be done much more efficiently, by not recalculating the primeness of every even number, or every multiple of 3, 5, 7, etc for every single number... See the Sieve of Eratosthenes (see eliben's implementation above), or even the Sieve of Atkin if you're feeling particularly brave and/or crazy.

    Caveat Emptor: I'm a python noob. Please don't take anything I say as gospel.

    0 讨论(0)
  • 2020-11-22 08:12

    Here is a numpy version of Sieve of Eratosthenes having both okay complexity (lower than sorting an array of length n) and vectorization.

    import numpy as np 
    def generate_primes(n):
        is_prime = np.ones(n+1,dtype=bool)
        is_prime[0:2] = False
        for i in range(int(n**0.5)+1):
            if is_prime[i]:
                is_prime[i*2::i]=False
        return np.where(is_prime)[0]
    

    Timings:

    import time    
    for i in range(2,10):
        timer =time.time()
        generate_primes(10**i)
        print('n = 10^',i,' time =', round(time.time()-timer,6))
    
    >> n = 10^ 2  time = 5.6e-05
    >> n = 10^ 3  time = 6.4e-05
    >> n = 10^ 4  time = 0.000114
    >> n = 10^ 5  time = 0.000593
    >> n = 10^ 6  time = 0.00467
    >> n = 10^ 7  time = 0.177758
    >> n = 10^ 8  time = 1.701312
    >> n = 10^ 9  time = 19.322478
    
    0 讨论(0)
  • 2020-11-22 08:13

    SymPy is a Python library for symbolic mathematics. It provides several functions to generate prime numbers.

    isprime(n)              # Test if n is a prime number (True) or not (False).
    
    primerange(a, b)        # Generate a list of all prime numbers in the range [a, b).
    randprime(a, b)         # Return a random prime number in the range [a, b).
    primepi(n)              # Return the number of prime numbers less than or equal to n.
    
    prime(nth)              # Return the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.
    prevprime(n, ith=1)     # Return the largest prime smaller than n
    nextprime(n)            # Return the ith prime greater than n
    
    sieve.primerange(a, b)  # Generate all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes. 
    

    Here are some examples.

    >>> import sympy
    >>> 
    >>> sympy.isprime(5)
    True
    >>> list(sympy.primerange(0, 100))
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    >>> sympy.randprime(0, 100)
    83
    >>> sympy.randprime(0, 100)
    41
    >>> sympy.prime(3)
    5
    >>> sympy.prevprime(50)
    47
    >>> sympy.nextprime(50)
    53
    >>> list(sympy.sieve.primerange(0, 100))
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
    
    0 讨论(0)
  • 2020-11-22 08:19

    python 3 (generate prime number)

    import math
    
    i = 2
    while True:
        for x in range(2, int(math.sqrt(i) + 1)):
            if i%x==0:
                break
        else:
            print(i)
        i += 1
    
    0 讨论(0)
提交回复
热议问题