Prime Number Generator in Python Complete Guide

Prime Number generator is a simple program in Python that lets you generate random or sequenced prime numbers using a Python Code.

In this tutorial, I will guide you through how you can generate the random prime number and sequenced prime number using Python.

Python Code for Prime Number Generator in Sequence

To generate Prime numbers in a sequence you can do this in a simple way which is a brute force method, then you can follow an efficient way in which we try to break the loop and proceed to the next element and third is the most efficient way where we are not using many iterations.

Let me guide you through a code for each of the cases here.

Using For Loop:

def findTheListofPrimeSimpleWay(tillRange):
    #Using For Loop
    #Initialize the List Element to store the prime number
    primeNumbers = []
    for eachPrime in range(2,tillRange+1):
        #let assume each element to be prime with this boolean variable
        numberIsPrime = True
        for number in range(2, eachPrime):
            #check if the number is divisible by any other number apart from itself.
            # If True then mark it as not prime.
            if eachPrime % number == 0:
                numberIsPrime =  False
            #if numeIfPrime still True after all the iteration then eachPrime is Prime Number.
        if numberIsPrime == True:
            primeNumbers.append(eachPrime)
    return primeNumbers

print(findTheListofPrimeSimpleWay(20))

As you can go through the above code in detail. But above code lacks efficiency. Since the second loop is the inner loop we are still checking the number even after it is marked as False.

To make it efficient, we can add an extra check to make the above loop end immediately after it marks a number as not prime. By doing this we are omitting extra checks which are unnecessary.

The Efficient Way

Let’s add that extra check in the above code to make it more efficient and remove extra iterations of the loop from this code.

def findTheListofPrimeEfficientWay(tillRange):
    #Using For Loop
    #Initialize the List Element to store the prime number
    primeNumbers = []
    for eachPrime in range(2,tillRange+1):
        #let assume each element to be prime with this boolean variable
        numberIsPrime = True
        for number in range(2, eachPrime):
            #check if the number is divisible by any other number apart from itself.
            # If True then mark it as not prime.
            if eachPrime % number == 0:
                numberIsPrime =  False
                break
            #if numeIfPrime still True after all the iteration then eachPrime is Prime Number.
        if numberIsPrime == True:
            primeNumbers.append(eachPrime)
    return primeNumbers

print(findTheListofPrimeEfficientWay(20))

The Most Effective Way to use Square Root

def findTheListofPrimeEffectiveWay(tillRange):
    #Using For Loop
    #Initialize the List Element to store the prime number
    primeNumbers = []
    for eachPrime in range(2,tillRange+1):
        #let assume each element to be prime with this boolean variable
        numberIsPrime = True
        #Dividing the Number till range of its square root.
        for number in range(2, int(eachPrime ** 0.5) + 1):
            #check if the number is divisible by any other number apart from itself.
            # If True then mark it as not prime.
            if eachPrime % number == 0:
                numberIsPrime =  False
                break
            #if numeIfPrime still True after all the iteration then eachPrime is Prime Number.
        if numberIsPrime == True:
            primeNumbers.append(eachPrime)
    return primeNumbers

print(findTheListofPrimeEffectiveWay(20))

Time Comparison

Let us compare the time it takes to find a total number of Prime numbers present in the range of 2 to 500. By adding timeit as an import library in the above code in order to check the current code efficiency.

So there are three programs currently written to find the list of prime numbers in a given range. Each function names are different refer the above programs.

Prime Number Generator in Python Complete Guide

As you can see from the above image. After I have added and run the above program. Each function took a different amount of time to get the list of prime numbers.

import timeit

def findTheListofPrimeSimpleWay(tillRange):
    #Using For Loop
    #Initialize the List Element to store the prime number
    primeNumbers = []
    for eachPrime in range(2,tillRange+1):
        #let assume each element to be prime with this boolean variable
        numberIsPrime = True
        for number in range(2, eachPrime):
            #check if the number is divisible by any other number apart from itself.
            # If True then mark it as not prime.
            if eachPrime % number == 0:
                numberIsPrime =  False
            #if numeIfPrime still True after all the iteration then eachPrime is Prime Number.
        if numberIsPrime == True:
            primeNumbers.append(eachPrime)
    return primeNumbers

def findTheListofPrimeEfficientWay(tillRange):
    #Using For Loop
    #Initialize the List Element to store the prime number
    primeNumbers = []
    for eachPrime in range(2,tillRange+1):
        #let assume each element to be prime with this boolean variable
        numberIsPrime = True
        for number in range(2, eachPrime):
            #check if the number is divisible by any other number apart from itself.
            # If True then mark it as not prime.
            if eachPrime % number == 0:
                numberIsPrime =  False
                break
            #if numeIfPrime still True after all the iteration then eachPrime is Prime Number.
        if numberIsPrime == True:
            primeNumbers.append(eachPrime)
    return primeNumbers

def findTheListofPrimeEffectiveWay(tillRange):
    #Using For Loop
    #Initialize the List Element to store the prime number
    primeNumbers = []
    for eachPrime in range(2,tillRange+1):
        #let assume each element to be prime with this boolean variable
        numberIsPrime = True
        for number in range(2, int(eachPrime ** 0.5) + 1):
            #check if the number is divisible by any other number apart from itself.
            # If True then mark it as not prime.
            if eachPrime % number == 0:
                numberIsPrime =  False
                break
            #if numeIfPrime still True after all the iteration then eachPrime is Prime Number.
        if numberIsPrime == True:
            primeNumbers.append(eachPrime)
    return primeNumbers

print(timeit.timeit('findTheListofPrimeSimpleWay(100)', globals=globals(), number = 10000))
print(findTheListofPrimeSimpleWay(500))
print(timeit.timeit('findTheListofPrimeEfficientWay(100)', globals=globals(), number = 10000))
print(findTheListofPrimeEfficientWay(500))
print(timeit.timeit('findTheListofPrimeEffectiveWay(100)', globals=globals(), number = 10000))
print(findTheListofPrimeEffectiveWay(500))

But here is the trick when I ran the program a second time with the addition of online to print the list as well. It took way less time, maybe it is my system.

Prime Number Generator in Python Complete Guide

Now to get the list of prime numbers in the range of 500, each program gave the same output but in different execution times. The first program took 2.9sec, the second took 0.95sec, and the third took 0.67 sec. So, you can see a significant decrease in the execution time using the efficient and effective way.

Random Prime Number Generator

Now using the above same program for a prime number generator, I will show you how can you generate random prime numbers whenever you run the function.

import random

def findTheListofPrimeEffectiveWay(isNunberPrime):
    numberIsPrime = True
    for number in range(2, int(isNunberPrime ** 0.5) + 1):
        #check if the number is divisible by any other number apart from itself.
        # If True then mark it as not prime.
        if isNunberPrime % number == 0:
            numberIsPrime =  False
            break
    #if numeIfPrime still True after all the iteration then eachPrime is Prime Number.
    if numberIsPrime == True:
        return True
    return False

def getRandomPrime(inRange):
    isNumberPrime = False
    getNumber = random.randint(2,inRange)
    while not isNumberPrime:
        isNumberPrime = findTheListofPrimeEffectiveWay(getNumber)
        if not isNumberPrime:
            getNumber = random.randint(2,inRange)
        #if Prime Number is found then return
        else:
            return getNumber
    

print(getRandomPrime(500))

So, in this above code, we have implemented a function to generate random numbers to a given range and generate a random prime number out of that range. This function keeps on running unless it finds a prime number in the given range.

Wrap Up

If you liked the answer then please follow us on Facebook, Twitter, and YouTube. Let us know the questions and answer you want to cover in this blog.

If you wanna check more Python-related posts then Read How to Check if Given Matrix is Invertible in Python.

Leave a Comment