Generate a random prime number

Use an integer seed. Count one iteration for every generated candidate, including the prime that ends the search.

Write a function named generate_random_prime that receives a seed and repeatedly generates random integers from 2 to 100, inclusive, until it finds a prime number. Stop when a prime is found and return a tuple containing the prime number and the number of iterations needed to find it. A caller can then print the result. For example, Python 3.11 produces the output in Listing 1 with Random(seed). Seed 53 appears twice and gives the same result both times.

Listing 1: Expected output for seeds 53, 45, 7, and 53 (Question 1).
Result with seed = 53
 - Random Prime Number: 29
 - #Iterations: 2
Result with seed = 45
 - Random Prime Number: 11
 - #Iterations: 9
Result with seed = 7
 - Random Prime Number: 43
 - #Iterations: 1
Result with seed = 53
 - Random Prime Number: 29
 - #Iterations: 2

The supplied is_prime helper keeps this exercise independent of any earlier prime-number task. Your work begins in generate_random_prime in Listing 2.

Listing 2: Starter code for generate_random_prime, with the is_prime helper supplied (Question 1).
from random import Random


def is_prime(n: int) -> bool:
    if n < 2:
        return False

    for divisor in range(2, int(n ** 0.5) + 1):
        if n % divisor == 0:
            return False

    return True


def generate_random_prime(seed: int) -> tuple[int, int]:
    # Add code here!
    pass


for seed in [53, 45, 7, 53]:
    prime, iterations = generate_random_prime(seed)
    print(f"Result with seed = {seed}")
    print(f" - Random Prime Number: {prime}")
    print(f" - #Iterations: {iterations}")
  • assert condition checks a Boolean condition. A true condition produces no output; a false condition raises AssertionError. For example, assert 2 + 3 == 5 passes.
  • Random(seed) creates a local generator. rng.randint(low, high) returns one integer from the inclusive bounds, which must satisfy low <= high. For example, rng.randint(5, 5) returns 5.
  • The supplied is_prime(n) receives an integer and returns True exactly when it is prime. Values below 2 return False. For example, is_prime(7) is True, and is_prime(9) is False. It changes no data.
  • In the helper, int(value) removes the fractional part of a positive number, and range(start, stop) supplies integers from start through stop - 1. For example, int(3.8) is 3, and list(range(2, 5)) is [2, 3, 4].
  • print(value) writes the value and a newline to the terminal. With several arguments, print(first, second) separates them with a space; for example, print(3, 5) displays 3 5. It returns None.