Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Prime or not in Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Every programmer comes across the problem of checking whether a number is prime and indeed it’s one of the basic level program in any language. I also tried it in many different languages, but the best language that I found to implement it is Python. It’s just one single line and the program does it all. Its so simple and smooth than other languages. The concept of Any and All has really reduced this problem to a single line and yes it is fast too. The logic used in this program is based on school method to check prime


# Returns true if n is prime else false
def prime(n):
    return all([(n % j) for j in range(2, int(n**0.5)+1)]) and n>1
# Driver code
n = 41
if prime(n):



Sieve of Eratosthenes:


The Sieve of Eratosthenes is an algorithm for finding all prime numbers up to a certain limit. It works by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with 2. Here’s an example implementation of this approach in Python:

Create a boolean list primes of size n+1, where primes[i] indicates whether i is prime or not. Initialize all values of primes to True, since initially all numbers are assumed to be prime. Mark the values of primes[0] and primes[1] to False, since 0 and 1 are not prime.

Iterate through the numbers from 2 to the square root of n. For each number i, if primes[i] is True, it means that i is prime. So, iterate over all multiples of i starting from i*i (because all smaller multiples of i have already been marked as composite by previous iterations), and mark them as composite by setting primes[j] to False.

Return a list of all numbers from 2 to n that are still marked as prime in the primes list.


def primes_sieve_eratosthenes(n):
    primes = [True] * (n+1)
    primes[0] = primes[1] = False
    for i in range(2, int(n**0.5)+1):
        if primes[i]:
            for j in range(i*i, n+1, i):
                primes[j] = False
    return [i for i in range(2, n+1) if primes[i]]
n = 20
primes = primes_sieve_eratosthenes(n)


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

the overall time complexity of the primes_sieve_eratosthenes(n) function is O(n log log n), which makes it very efficient for finding primes up to large values of n.

 The space complexity is O(n), which is reasonable for most practical applications.

This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Last Updated : 10 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials