Python classic 100 questions about printing prime numbers

Question: Find all prime numbers between 1-N and output all prime numbers.

A prime number, also known as a prime number, refers to an integer that is only divisible by 1 and itself, that is, a positive integer that has no other factors except 1 and itself. For example, 2, 3, 5, 7, 11, etc. are all prime numbers. Any positive integer greater than 1 can be obtained by multiplying prime numbers, so prime numbers have important mathematical meaning.

Method 1: Violent enumeration method

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

def find_prime(n):
    prime_list = []
    for i in range(2, n):
        if is_prime(i):
            prime_list.append(i)
    return prime_list

Advantages: Simple to implement and easy to understand.

Disadvantages: The time complexity is high and it cannot handle a large range of prime numbers.

Method 2: Optimize enumeration method

def find_prime(n):
    prime_list = []
    for i in range(2, n):
        j = 2
        while j <= int(i ** 0.5):
            if i % j == 0:
                break
            j += 1
        if j > int(i ** 0.5):
            prime_list.append(i)
    return prime_list

Advantages: Some repeated calculations are reduced and the time complexity is reduced.

Disadvantages: Still cannot handle larger prime ranges.

Method three: Ehrlich sieve method

def find_prime(n):
    prime_list = []
    is_prime = [True] * (n+1)
    for i in range(2, n+1):
        if is_prime[i]:
            prime_list.append(i)
            for j in range(i*i, n+1, i):
                is_prime[j] = False
    return prime_list

Advantages: lower time complexity and can handle a larger range of prime numbers.

Disadvantages: The space complexity is high and an array of size (n+1) is required to determine whether it is a prime number.

Method 4: Euler Sieve Method

def find_prime(n):
    prime_list = []
    is_prime = [True] * (n+1)
    for i in range(2, n+1):
        if is_prime[i]:
            prime_list.append(i)
        for j in range(len(prime_list)):
            if i * prime_list[j] > n:
                break
            is_prime[i * prime_list[j]] = False
            if i % prime_list[j] == 0:
                break
    return prime_list

Advantages: lower time complexity and lower space complexity.

Disadvantages: The implementation is more complex and requires screening of known prime numbers.

Guess you like

Origin blog.csdn.net/yechuanhui/article/details/132852726