[docs]defget_prime_numbers(n:int)->list[int]:"""Get a given number of prime numbers. :param n: Number of primes that are requested. :return: List with prime numbers. :raise BiogemeError: If the requested number is non-positive. """ifnotisinstance(n,int)orn<=0:raiseBiogemeError(f'Incorrect number: {n}')# Initial setup based on known distribution of primes for efficiencyifn==1:return[2]# The first prime number is 2estimated_upper_bound=n*(np.log(n)+np.log(np.log(n)))# Estimation based on the prime number theoremprimes=calculate_prime_numbers(int(estimated_upper_bound))# In case the estimation was too low, which is very rare, increase until enough primes are foundwhilelen(primes)<n:estimated_upper_bound*=1.5primes=calculate_prime_numbers(int(estimated_upper_bound))returnprimes[:n]
[docs]defcalculate_prime_numbers(upper_bound:int)->list[int]:"""Calculate prime numbers up to a specified upper bound using the Sieve of Eratosthenes. :param upper_bound: Prime numbers up to this value will be computed. :return: A list of prime numbers up to the upper bound. :raise BiogemeError: If the sqrt_max is incorrectly defined (e.g., negative number). """ifnotisinstance(upper_bound,int)orupper_bound<0:raiseBiogemeError(f'Incorrect value: {upper_bound}')ifupper_bound<2:return[]# There are no prime numbers less than 2# Initialize a list indicating whether numbers are primeis_prime=[False,False]+[True]*(upper_bound-1)# 0 and 1 are not prime, others assumed prime initiallyfornumberinrange(2,int(np.sqrt(upper_bound))+1):# Check up to the square root of the sqrt_maxifis_prime[number]:# Found a primeformultipleinrange(number*number,upper_bound+1,number):# Mark multiples of the prime as non-primeis_prime[multiple]=False# Extract prime numbers based on the boolean listprimes=[numfornum,primeinenumerate(is_prime)ifprime]returnprimes