简体   繁体   English

使用不同的方法来查找素数,通过从列表中删除所有素数的倍数

[英]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.这是 SoE的一个实现,您可能会发现它更直接且易于理解。

Essentially, a list of 1s is created, with the length of the requested array.本质上,创建了一个 1 的列表,其中包含所请求数组的长度。 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.另一个特性是,素数列表可以作为二进制索引(1 = 素数,0 = 复合)或素数本身的列表返回。

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:非常感谢您的评论,@JohnnyMopp @Dominique 我已经更正了代码:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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