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.
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.
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}")
TipHint
assert conditionchecks a Boolean condition. A true condition produces no output; a false condition raisesAssertionError. For example,assert 2 + 3 == 5passes.Random(seed)creates a local generator.rng.randint(low, high)returns one integer from the inclusive bounds, which must satisfylow <= high. For example,rng.randint(5, 5)returns5.- The supplied
is_prime(n)receives an integer and returnsTrueexactly when it is prime. Values below2returnFalse. For example,is_prime(7)isTrue, andis_prime(9)isFalse. It changes no data. - In the helper,
int(value)removes the fractional part of a positive number, andrange(start, stop)supplies integers fromstartthroughstop - 1. For example,int(3.8)is3, andlist(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)displays3 5. It returnsNone.