Project Euler Problem 7 Solution

Project Euler Problem 7 Solution

Find the 10001st prime number

by {BetaProjects} | Project Euler & HackerRank

Project Euler 7 Statement

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 10001st prime number?

Solution

The quickest and easiest way to solve both this problem and the HackerRank version is to build a list of prime numbers. We can use that list’s index (or ordinal position) to find the Nth prime number. The only concern is to make sure we generate enough prime numbers to satisfy all the queries.

Our prime number generator is fast and can generate 20 million primes in less than one–half second. But, it generates prime numbers below some numerical upper bound and not a specific number of primes. Calling our function as prime_sieve(10001) will return a list of all primes below 10,001 or 1,229 prime numbers. We are, therefore, left with the task of calculating our upper bound to include at least 10,001 primes.

Prime counting function

The Prime Counting Function, π(x) gives the number of primes less than or equal to a given number x. So, the inverse, π−1(n), takes a number of primes and gives us an x, which is the upper bound used for our prime_sieve() function. For more information, there is a calculator here.

The calculator reports that there are 10,024 primes less than 105,000 which cover both this problem and the HackerRank version.

HackerRank version

HackerRank runs 1,000 test cases to find prime numbers within a limit, 1≤N≤10,000.

Python Source Code

from Euler import prime_sieve
# Add and extra element to the front of our list to base it from 1 and not 0
prime = [0]+prime_sieve(105000) 
n = int(input('nth prime number (≤10001)? '))
print ("Prime number", n, "is", prime[n])	

Last Word