Sieve of Eratosthenes (find prime numbers smaller than N)

Given a number (n), find all the prime numbers smaller than or equal to n.

Sieve of Eratosthenes is one of the most efficient algorithms to find all prime numbers smaller than or equal to n. when n is smaller than 10 million or so.

A prime number is a number divisible only by itself and one.
Example 13, 17, 7, etc.

Algorithm:

We use a boolean array which has a size of N i.e. arr[1...n].

We start from 2 and make the array value false for all the indexes which are multiples of 2.
credits: GeeksForGeeks

We find the next element in the array which is True. This is our next prime number i.e. 3.
We make the array value false for all the indexes which are multiples of 3.
credits: GeeksForGeeks
And then again find the next True value which is the next prime number.
We repeat this process until we reach n.

At the end, all the values in the array which are True have a prime index value.

Optimization:

Rather than running the loop for prime p from (2*p to n) we can start making values False from p*p = (p2 to n) as all the values from (2*p to p2) will actually be made False already by previous prime numbers because of the property that all numbers are product of two or more prime numbers.

Code in Python:

# Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.
""" The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is
smaller than 10 million or so """


# function to find prime numbers less than or equal to num
def find_primes_sieve(num):
    # list of all numbers upto n
    intList = [True for i in range(num+1)]

    # first prime
    p = 2

    while p * p <= num:

        # if intList[p] is True means its a prime number
        if intList[p]:
            for i in range(p**2, num+1, p):
                intList[i] = False

        p += 1

    lis = []
    for i in range(2, len(intList)):
        if intList[i]:
            lis.append(i)

    return lis


primes = find_primes_sieve(30)
print(primes)
"""
Outputs:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
"""

--
Have any questions or suggestions? Post in the comments below!!

By,
Anubhav Shrimal

Comments

Popular posts from this blog

Reverse alternate k nodes in a linked list

Sorted Array: Binary Search

Tree data structure