简体   繁体   中英

Using a different approach to find prime number, by removing all the multiples of prime number from a list

I am getting multiple errors while running this code, Please help me understand what the problem is?

    def first_prime_fn(first,last):
    for x in range (first,last):
        for y in range (2,x):
            if x % y == 0:
                break
        else:
            prime = x
            return prime

def remove_multiple(num, lst):
    for n in range(2, len(lst)):
        if n * num in lst:
            lst.remove(num * n)
    return lst


def prime_finder(start,end):
    prime_list = [x for x in range (start, end+1)]
    for n in range(start,end):
        prime = first_prime_fn(n, end)
        remove_multiple(prime,prime_list)
    print(prime_list)

prime_finder(4,100)
Traceback (most recent call last):
   File "script.py", line 24, in <module>
     prime_finder(4,100)
   File "script.py", line 21, in prime_finder
     remove_multiple(prime,prime_list)
   File "script.py", line 12, in remove_multiple
     if n * num in lst: TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Here is an implementation of the SoE, which you might find more straight-forward and easy to follow.

Essentially, a list of 1s is created, with the length of the requested array. Then each multiple (up to the square root of the value) is cancelled out (changed to a zero).

An additional feature, is that the list of prime numbers can be returned either as a binary index (1 = prime, 0 = composite), or a list of the prime numbers themselves.

Example code:

def esieve(n: int, deindex: bool=True) -> list:
    """Deriviative of the Sieve of Eratosthenes.

    Args:
        n (int): Calculate primes to this number, inclusive.
        deindex (bool, optional): Return list of prime numbers, not a binary 
            index. Defaults to True.

    Design based on:
        https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

    Returns:
        list: A list of prime numbers (or indexes) up to (n), inclusive.

    """
    # Initialise prime list to 1s.
    P = [1 for _ in range(n+1)]
    # Create the sieve.
    for i in range(2, int(n**0.5)+1):
        if P[i]:
            for j in range(i*i, n+1, i):
                P[j] = 0
    P[0] = 0
    P[1] = 0
    if deindex:
        # Replace binary indexes with prime numbers.
        P = [i for i in range(n+1) if P[i]]
    return P

Usage:

>>> esieve(15, False)
[0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0]

>>> esieve(15, True)
[2, 3, 5, 7, 11, 13]

thank you so much for your comments, @JohnnyMopp @Dominique I have corrected the code:

def first_prime_fn(first,last):
    #returning the first prime number in the given range
    for x in range (first,last):
        for y in range (2,x):
            if x % y == 0:
                break
        else:
            prime = x
            return prime

def remove_multiple(num, lst):
    #removing multiples of a number from a list
    for n in range(2, len(lst)):
        if n * num in lst:
            lst.remove(num * n)
    return lst


def prime_finder(start,end):
    print("Using Sieve of Eratosthenes to find prime number list")
    if start > 2:
        prime_list = [x for x in range (start, end+1)]
    elif start < 2:
        prime_list = [ x for x in range (2, end+1)]

    for n in range(2,end):
        prime = first_prime_fn(n, end)
        if prime == None:
            break
        else:
            remove_multiple(prime,prime_list)
    print(prime_list)

prime_finder(20,50)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM