Open In App

Prime or not in Python

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Python




# 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):
    print("Yes")
else:
    print("No")


Output

Yes

Sieve of Eratosthenes:

Approach:

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.

Python3




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)
print(primes)


Output

[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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads