5 Best Ways to Write a Program in Python to Generate Any Random Five Prime Numbers Between 100 to 150 in a Series

Rate this post

πŸ’‘ Problem Formulation: The task at hand is to develop a Python program that is capable of generating a sequence of five random prime numbers within the range of 100 to 150. The desired output is a series where each element is a unique prime number such as [101, 107, 113, 131, 149].

Method 1: Brute Force Approach

Using a brute force approach, we can iterate through numbers between 100 to 150, check each for primality, and accumulate a list of prime numbers. Then, we randomly select five from this list. This method relies on checking factors of each candidate number to determine if it is prime.

Here’s an example:

import random 

def is_prime(n):
    if n <= 1: 
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0: 
            return False
    return True

def generate_primes(start, end, num):
    primes = [i for i in range(start, end + 1) if is_prime(i)]
    return random.sample(primes, num)

five_primes = generate_primes(100, 150, 5)

Output: [103, 107, 113, 137, 149]

This code snippet defines two functions: is_prime() to check primality and generate_primes() to generate the prime series. The generate_primes() function creates a list of prime numbers between the given start and end and then uses random.sample() to pick five unique primes.

Method 2: Sieve of Eratosthenes

Implementing the Sieve of Eratosthenes algorithm, which systematically eliminates the non-prime numbers, is a time-efficient way to find all primes within a given range. From this list, five primes are randomly chosen.

Here’s an example:

import random 

def sieve_of_eratosthenes(end):
    prime = [True for i in range(end+1)]
    p = 2
    while (p * p <= end):
        if (prime[p] == True):
            for i in range(p * p, end+1, p):
                prime[i] = False
        p += 1
    return [p for p in range(100, end) if prime[p]]

random_primes = random.sample(sieve_of_eratosthenes(150), 5)

Output: [101, 103, 109, 127, 139]

The sieve_of_eratosthenes() function generates a list of booleans where the index is marked False if it is not a prime and True if it is a prime. We then create a list of prime numbers from 100 to 150 and select five random primes from it.

Method 3: Increment and Check

By incrementing from the lowest possible prime within the range, checking each for primality, and stopping when enough primes are found, this method ensures fewer calculations than a brute force across the entire range. This is a hybrid between brute force and optimization.

Here’s an example:

import random

def is_prime(num):
    return all(num % i != 0 for i in range(2, int(num ** 0.5) + 1))

primes = []
number = 101
while len(primes) < 5:
    if is_prime(number):
    number += 2  # increment by 2, since even numbers are not prime

random_primes = primes

Output: [101, 103, 107, 109, 113]

The is_prime() function returns True if a number is prime, which is confirmed by trying to divide by all numbers up to its square root. By incrementing number by 2, we ensure only odd numbers are checked (as even numbers cannot be prime), which reduces computational load.

Method 4: Using itertools and Optimized Prime Check

Utilizing Python’s itertools module, we can create efficient loops for generating primes. The islice function ensures we inspect only the numbers within the specified range, and an optimized prime check reduces the number of divisions we need to perform.

Here’s an example:

import random
from itertools import islice, count

def is_prime(n):
    return n > 1 and all(n % i for i in islice(count(2), int(n**0.5)-1))

primes = [n for n in islice(count(100), 50) if is_prime(n)]
five_primes = random.sample(primes, 5)

Output: [107, 109, 113, 131, 149]

This code snippet uses itertools to efficiently create an iterator that starts counting from 100. For each number, the is_prime() function determines if it is prime by checking if it has no divisors up to its square root. Finally, five primes are chosen at random from the list of primes.

Bonus One-Liner Method 5: Comprehension and Randomness

A compact one-liner method combines list comprehension with random.sample to filter and select primes with minimal code.

Here’s an example:

import random

five_primes = random.sample([p for p in range(100, 151) if all(p % d != 0 for d in range(2, int(p**0.5) + 1))], 5)

Output: [101, 103, 107, 127, 139]

This example utilizes a list comprehension inside the random.sample() function to check each number between 100 and 150 for primality before randomly selecting five primes. It’s an elegant solution but may not be as readable for those unfamiliar with comprehensions.


  • Method 1: Brute Force Approach. Straightforward but potentially inefficient for larger ranges. Good for small datasets.
  • Method 2: Sieve of Eratosthenes. Extremely efficient for generating many primes. Overkill for this particular task but great for educational purposes.
  • Method 3: Increment and Check. Balances between efficiency and simplicity. Less work than brute force but can be slow for large datasets.
  • Method 4: Using itertools and Optimized Prime Check. Offers high efficiency with advanced Python features. Best for those comfortable with itertools and generator expressions.
  • Bonus One-Liner Method 5: Comprehension and Randomness. Quick and concise. Ideal for compact code but sacrifices some readability and may be slower than other methods.