JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Generating Random Prime Numbers in Python

Author:JIYIK Last Updated:2025/05/06 Views:

This tutorial demonstrates methods to generate and output any random prime number in Python.

Prime numbers are very useful constants used in programming, especially in cryptography. The use of prime numbers is crucial in encryption and hashing as they can be used to encrypt and hash sensitive data and prevent them from being decrypted at will.


Create a function to generate random prime numbers in a given range

A prime number has only 2 factors (a factor is a number that can be divided by another number and still leave a whole number). A prime number can only be divided by 1 and itself.

It is technically impossible to generate a random prime number from 0 to infinity, as it would require a lot of processing power to keep it that large.

For this reason, we need to include a range of numbers as parameters to collect prime numbers within the set range.

The first thing to do is to create a function to collect all the prime numbers in a given range into a list. For this function, loop over all the numbers in the range and check if only 1 and itself are divisible.

def primesInRange(x, y):
    prime_list = []
    for n in range(x, y):
        isPrime = True

        for num in range(2, n):
            if n % num == 0:
                isPrime = False

        if isPrime:
            prime_list.append(n)

    return prime_list


print(primesInRange(100, 250))

The output will print all the prime numbers from the given range 100 to 250.

Output:

[101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241]

The next step is primesInRange()to generate a random number within the range of prime numbers returned by the function.

Under the Python randommodule, it has a choice()function called which selects a random element from a given iterable or sequence.

Given the function implemented above primesInRange(), capture the return value using a list variable and use random.choice()to select a random prime number from the list. choice()Before using the function, don’t forget to import randomthe module.

import random

prime_list = primesInRange(100, 250)
randomPrime = random.choice(prime_list)

print("Generated random prime number: ", randomPrime)

Sample random output:

Generated random prime number:  191

Here is the full source code for this solution.

import random


def primesInRange(x, y):
    prime_list = []
    for n in range(x, y):
        isPrime = True

        for num in range(2, n):
            if n % num == 0:
                isPrime = False

        if isPrime:
            prime_list.append(n)
    return prime_list


prime_list = primesInRange(100, 250)
randomPrime = random.choice(prime_list)

print("Generated random prime number: ", randomPrime)

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Writing logs to a file in Python

Publish Date:2025/05/06 Views:132 Category:Python

This tutorial will show you how to write logs to files in Python. Use the module in Python logging to write logs to files Logging is used to debug a program and find out what went wrong. logging The log module is used to log data to a file

Comparing two dates in Python

Publish Date:2025/05/06 Views:97 Category:Python

This tutorial explains how to compare two dates in Python. There are multiple ways to determine which date is greater, so the tutorial also lists different sample codes to illustrate the different methods. Comparing two dates in Python usin

Reload or unimport modules in Python

Publish Date:2025/05/06 Views:58 Category:Python

Modules allow us to store definitions of different functions and classes in Python files, which can then be used in other files. pandas , NumPy , scipy , Matplotlib are the most widely used modules in Python. We can also create our own modu

Pausing program execution in Python

Publish Date:2025/05/06 Views:156 Category:Python

This tutorial will demonstrate various ways to pause a program in Python. Pausing the execution of a program or application is used in different scenarios, such as when a program requires user input. We may also need to pause the program fo

Importing modules from a subdirectory in Python

Publish Date:2025/05/06 Views:190 Category:Python

This tutorial will explain various ways to import modules from subdirectories in Python. Suppose we have a file in a subdirectory of our project directory and we want to import this file and use its methods in our code. We can import files

Sleeping for a number of milliseconds in Python

Publish Date:2025/05/06 Views:124 Category:Python

In this tutorial, we will look at various ways to pause or suspend the execution of a program in Python for a given amount of time. Let's say we want to pause the execution of a program for a few seconds to let the user read instructions ab

Python Numpy.pad Function

Publish Date:2025/05/06 Views:104 Category:Python

In Python, we have NumPy the array module to create and use arrays. Arrays can have different sizes and dimensions. Padding is a useful method that can be used to compensate for the size of an array. We can mutate an array and add some padd

Generating Random Colors in Python

Publish Date:2025/05/06 Views:135 Category:Python

In the digital world, colors are represented in different formats. RGB, Hexadecimal format are just some of the commonly used formats. In this tutorial, we will learn how to generate random colors in Python. When we talk about generating ra

Getting the name of a class in Python

Publish Date:2025/05/06 Views:83 Category:Python

Just like object constructors, classes can be defined as user-defined prototypes for creating objects. class Classes can be created using the keyword . A class is a data structure that can contain both data members and member methods. This

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial