Finding Prime Numbers in Python

  • Share this:

Code introduction


This function returns a list of all prime numbers less than or equal to n.


Technology Stack : Built-in list, loop, conditional judgment

Code Type : Function

Code Difficulty : Intermediate


                
                    
def get_primes(n):
    if n < 2:
        return []
    sieve = [True] * (n + 1)
    for i in range(2, int(n ** 0.5) + 1):
        if sieve[i]:
            for j in range(i*i, n + 1, i):
                sieve[j] = False
    return [i for i in range(2, n + 1) if sieve[i]]