Euler Problem 7

Back to overview.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

We reuse our prime functions and use a trick from stackoverflow to get the nth element.

In [7]:
import itertools

def is_prime(n, smaller_primes):
    for s in smaller_primes:
        if n % s == 0:
            return False
        if s * s > n:
            return True
    return True

def prime_generator_function():
    primes = [2, 3, 5, 7]
    for p in primes:
        yield p
    while True:
        p += 2
        if is_prime(p, primes):
            primes.append(p)
            yield p

def get_nth_prime(n):
    ps = prime_generator_function()
    return next(itertools.islice(ps, n - 1, n))

assert(get_nth_prime(6) == 13)
print(get_nth_prime(10001))
104743