Simple prime number generator in Python

前端 未结 26 1777
感情败类
感情败类 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:04

    There are some problems:

    • Why do you print out count when it didn't divide by x? It doesn't mean it's prime, it means only that this particular x doesn't divide it
    • continue moves to the next loop iteration - but you really want to stop it using break

    Here's your code with a few fixes, it prints out only primes:

    import math
    
    def main():
        count = 3
        
        while True:
            isprime = True
            
            for x in range(2, int(math.sqrt(count) + 1)):
                if count % x == 0: 
                    isprime = False
                    break
            
            if isprime:
                print count
            
            count += 1
    

    For much more efficient prime generation, see the Sieve of Eratosthenes, as others have suggested. Here's a nice, optimized implementation with many comments:

    # Sieve of Eratosthenes
    # Code by David Eppstein, UC Irvine, 28 Feb 2002
    # http://code.activestate.com/recipes/117119/
    
    def gen_primes():
        """ Generate an infinite sequence of prime numbers.
        """
        # Maps composites to primes witnessing their compositeness.
        # This is memory efficient, as the sieve is not "run forward"
        # indefinitely, but only as long as required by the current
        # number being tested.
        #
        D = {}
        
        # The running integer that's checked for primeness
        q = 2
        
        while True:
            if q not in D:
                # q is a new prime.
                # Yield it and mark its first multiple that isn't
                # already marked in previous iterations
                # 
                yield q
                D[q * q] = [q]
            else:
                # q is composite. D[q] is the list of primes that
                # divide it. Since we've reached q, we no longer
                # need it in the map, but we'll mark the next 
                # multiples of its witnesses to prepare for larger
                # numbers
                # 
                for p in D[q]:
                    D.setdefault(p + q, []).append(p)
                del D[q]
            
            q += 1
    

    Note that it returns a generator.

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

    To my opinion it is always best to take the functional approach,

    So I create a function first to find out if the number is prime or not then use it in loop or other place as necessary.

    def isprime(n):
          for x in range(2,n):
            if n%x == 0:
                return False
        return True
    

    Then run a simple list comprehension or generator expression to get your list of prime,

    [x for x in range(1,100) if isprime(x)]
    
    0 讨论(0)
  • 2020-11-22 08:04

    For me, the below solution looks simple and easy to follow.

    import math
    
    def is_prime(num):
    
        if num < 2:
            return False
    
        for i in range(2, int(math.sqrt(num) + 1)):
            if num % i == 0:
                return False
    
    return True
    
    0 讨论(0)
  • 2020-11-22 08:05

    Another simple example, with a simple optimization of only considering odd numbers. Everything done with lazy streams (python generators).

    Usage: primes = list(create_prime_iterator(1, 30))

    import math
    import itertools
    
    def create_prime_iterator(rfrom, rto):
        """Create iterator of prime numbers in range [rfrom, rto]"""
        prefix = [2] if rfrom < 3 and rto > 1 else [] # include 2 if it is in range separately as it is a "weird" case of even prime
        odd_rfrom = 3 if rfrom < 3 else make_odd(rfrom) # make rfrom an odd number so that  we can skip all even nubers when searching for primes, also skip 1 as a non prime odd number.
        odd_numbers = (num for num in xrange(odd_rfrom, rto + 1, 2))
        prime_generator = (num for num in odd_numbers if not has_odd_divisor(num))
        return itertools.chain(prefix, prime_generator)
    
    def has_odd_divisor(num):
        """Test whether number is evenly divisable by odd divisor."""
        maxDivisor = int(math.sqrt(num))
        for divisor in xrange(3, maxDivisor + 1, 2):
            if num % divisor == 0:
                return True
        return False
    
    def make_odd(number):
        """Make number odd by adding one to it if it was even, otherwise return it unchanged"""
        return number | 1
    
    0 讨论(0)
  • 2020-11-22 08:08

    Just studied the topic, look for the examples in the thread and try to make my version:

    from collections import defaultdict
    # from pprint import pprint
    
    import re
    
    
    def gen_primes(limit=None):
        """Sieve of Eratosthenes"""
        not_prime = defaultdict(list)
        num = 2
        while limit is None or num <= limit:
            if num in not_prime:
                for prime in not_prime[num]:
                    not_prime[prime + num].append(prime)
                del not_prime[num]
            else:  # Prime number
                yield num
                not_prime[num * num] = [num]
            # It's amazing to debug it this way:
            # pprint([num, dict(not_prime)], width=1)
            # input()
            num += 1
    
    
    def is_prime(num):
        """Check if number is prime based on Sieve of Eratosthenes"""
        return num > 1 and list(gen_primes(limit=num)).pop() == num
    
    
    def oneliner_is_prime(num):
        """Simple check if number is prime"""
        return num > 1 and not any([num % x == 0 for x in range(2, num)])
    
    
    def regex_is_prime(num):
        return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None
    
    
    def simple_is_prime(num):
        """Simple check if number is prime
        More efficient than oneliner_is_prime as it breaks the loop
        """
        for x in range(2, num):
            if num % x == 0:
                return False
        return num > 1
    
    
    def simple_gen_primes(limit=None):
        """Prime number generator based on simple gen"""
        num = 2
        while limit is None or num <= limit:
            if simple_is_prime(num):
                yield num
            num += 1
    
    
    if __name__ == "__main__":
        less1000primes = list(gen_primes(limit=1000))
        assert less1000primes == list(simple_gen_primes(limit=1000))
        for num in range(1000):
            assert (
                (num in less1000primes)
                == is_prime(num)
                == oneliner_is_prime(num)
                == regex_is_prime(num)
                == simple_is_prime(num)
            )
        print("Primes less than 1000:")
        print(less1000primes)
    
        from timeit import timeit
    
        print("\nTimeit:")
        print(
            "gen_primes:",
            timeit(
                "list(gen_primes(limit=1000))",
                setup="from __main__ import gen_primes",
                number=1000,
            ),
        )
        print(
            "simple_gen_primes:",
            timeit(
                "list(simple_gen_primes(limit=1000))",
                setup="from __main__ import simple_gen_primes",
                number=1000,
            ),
        )
        print(
            "is_prime:",
            timeit(
                "[is_prime(num) for num in range(2, 1000)]",
                setup="from __main__ import is_prime",
                number=100,
            ),
        )
        print(
            "oneliner_is_prime:",
            timeit(
                "[oneliner_is_prime(num) for num in range(2, 1000)]",
                setup="from __main__ import oneliner_is_prime",
                number=100,
            ),
        )
        print(
            "regex_is_prime:",
            timeit(
                "[regex_is_prime(num) for num in range(2, 1000)]",
                setup="from __main__ import regex_is_prime",
                number=100,
            ),
        )
        print(
            "simple_is_prime:",
            timeit(
                "[simple_is_prime(num) for num in range(2, 1000)]",
                setup="from __main__ import simple_is_prime",
                number=100,
            ),
        )
    

    The result of running this code show interesting results:

    $ python prime_time.py
    Primes less than 1000:
    [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, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
    
    Timeit:
    gen_primes: 0.6738066330144648
    simple_gen_primes: 4.738092333020177
    is_prime: 31.83770858097705
    oneliner_is_prime: 3.3708438930043485
    regex_is_prime: 8.692703998007346
    simple_is_prime: 0.4686249239894096
    

    So I can see that we have right answers for different questions here; for a prime number generator gen_primes looks like the right answer; but for a prime number check, the simple_is_prime function is better suited.

    This works, but I am always open to better ways to make is_prime function.

    0 讨论(0)
  • 2020-11-22 08:10
    • The continue statement looks wrong.

    • You want to start at 2 because 2 is the first prime number.

    • You can write "while True:" to get an infinite loop.

    0 讨论(0)
提交回复
热议问题