Screening Method for Finding Prime Numbers and the Application of Iterators and Generators

Posted by php_blob on Sat, 07 Sep 2019 07:10:36 +0200

The method of finding prime numbers by sieving is: sieving prime numbers to sum numbers: starting with the first prime number 2, remove its multiples; so that the first non-zero number after two must be prime numbers, and delete its multiples... Repeat the deletion process until a non-zero number is not found after the prime number is found. Output all non-zero numbers.

Find a list of prime numbers no larger than natural number n

def find_primes(n):
    myset = [i for i in range(2, n+1)]

    primes = [2]
    while True:
        num = primes[-1]
        for i in myset:
            if i % num == 0:
                myset.remove(i) # Lists can be changed during queries, but dictionaries can't.
        if len(myset) == 0:  # All the figures have been checked.  
            break
        else:
            primes.append(myset[0]) # The smallest remaining number, which can be identified as a prime, is added to the list of prime numbers.
    return primes 

print(find_primes(20))

[2, 3, 5, 7, 11, 13, 17, 19]

Find the nth prime

def find_nth_primes(n: int):
    if n <= 0:
        return None
    if n == 1:
        return 2
    primes = [2]
    
    number2check = 3
    numberprime = 1
    while True:
        is_prime = True
        for prim in primes:
            if number2check % prim == 0:
                is_prime = False
                break
        if is_prime:
            primes.append(number2check)
            numberprime += 1
            if numberprime == n:
                return number2check
        number2check += 1

Primes Finding Based on Generator

Generator and iterator concepts: https://foofish.net/iterators-vs-generators.html

import itertools
def odd_iter():
    return itertools.count(3,1)  # Generate an integer from small to large
def not_divisable(n):
    return lambda x:x %n>0
def primes():
    yield 2
    it = odd_iter()
    it = filter(not_divisable(2),it) # Filter out what can be divisible by two.
    while True:
        n = next(it)
        yield n
        it = filter(not_divisable(n),it) # Filtered out that can be divisible by n
p = primes()
for t in range(100):
    print(next(p))

The iterator is implemented by a generator as follows:

def primes():  
    def next_N():
        n = 3
        while True:
            yield n
            n += 1
    def not_divisable(n):
        f = lambda x:x % n > 0
        return f    
    
    yield 2
    it = next_N()
    it = filter(not_divisable(2),it) # Filter out what can be divisible by two.
    while True:
        n = next(it)
        yield n
        it = filter(not_divisable(n),it) # Filtered out that can be divisible by n
        
        
p = primes()
s = ''
for t in range(1000):
    s = s + ', '+ str(next(p)) if s != '' else str(next(p))
print(s)

Generators and Iterators and Lazy Objects (Reference: https://blog.csdn.net/IaC743nj0b/article/details/79547122)

  • Range objects in Python 3 (xrange objects in Python 2) are lazy, but range objects are not iterators. Range and iterators are both "inert", but they achieve "inertia" in quite different ways.
  • The only thing you can do with an iterator is to get its next element (iter). If there are no more elements, a stop iteration exception will be thrown.
  • The iterator is stateful. After iterating through an iterator once, if you try to loop again, it will be empty. The iterator is an inert one-time Iterable object. "Inertia" is because they only iterate over projects, "single use" is because once an element is "consumed" from an iterator, it disappears forever.
  • Generators (whether from generator functions or generator expressions) are a simple way to create iterators.
  • Range is an iterative object, but the range object itself is not an iterator. We cannot call next on the range object.
  • Unlike iterators, we can traverse a range object without "consuming" it.

Topics: Lambda Python