def find_nth_prime(nth_prime): """ Function returns the nth prime of the natural numbers. :param nth_prime: {int} is nth prime to return in natural numbers :return: {int} the nth prime in natural numbers """ # check input, raise relevant errors if type(nth_prime) != int: raise TypeError("Input param 'nth_prime' was not type of int") if nth_prime <= 0: raise ValueError("Input param 'nth_prime' was a negative/zero value") # by the prime number theorem: # n(lnn) + n((ln(lnn))−1) < pn < n(lnn) + n(ln(lnn)), where n=nth, pn=nth prime for n≥6 if nth_prime >= 6: upper_bound = math.ceil(nth_prime * math.log(nth_prime) + nth_prime * math.log(math.log(nth_prime))) # else the 5th prime caps at 11 else: upper_bound = 11 # get all primes up to the calculated possible upper bound of the nth prime primes = eratosthenes_primes(upper_bound) # return the nth prime from calculated primes return primes[nth_prime - 1]
def summation_of_primes(limit): """ Function will sum all of the primes up to and including the limit given Uses the sieve of eratosthenes to generate primes :param limit: {int} :return: {int} sum of primes up tp limit """ # check input, raise relevant errors if type(limit) != int: raise TypeError("Input param 'limit' was not type of int") # initialize sum and get all primes prime_sum = 0 primes = eratosthenes_primes(limit) # add up all primes for prime in primes: prime_sum = prime_sum + prime return prime_sum
def test_input_one(self): self.assertEqual(eratosthenes_primes(1), [])
def test_input_two(self): self.assertEqual(eratosthenes_primes(2), [2])
def test_input_zero(self): self.assertEqual(eratosthenes_primes(0), [])
def test_input_negative(self): self.assertEqual(eratosthenes_primes(-1), [])
def test_large_non_prime(self): self.assertEqual(eratosthenes_primes(102), [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 ])
def test_small_non_prime(self): self.assertEqual(eratosthenes_primes(12), [2, 3, 5, 7, 11])
def test_small_prime(self): self.assertEqual(eratosthenes_primes(7), [2, 3, 5, 7])