Craig Andrews

I am a developer. I do code and things.

Navigation
 » Home
 » About Me
 » Projects
 » Github
 » XML Feed

Problem 7 - 10001st prime

31 May 2016 » python, euler

Problem 7 is one that we accidentally solved back in problem 3, the prime factors. Using the Sieve of Eratosthenes we can generate a lot of primes really quickly. Well, I say really quickly. Maybe not quickly enough.

Here is the basic implementation, using a handy new function I added to euler.iter called take that allows n values to be removed from the front of a given iterator or sequence.

    from euler.prime import sieve
    from euler.iter import take, last


    def nth_prime(n):
        return last(take(sieve(104744), n))
    

This returns the correct answer of 104744 in 46ms. The sole reason for this is that I knew what the answer was and set up the sieve accordingly. Setting the value higher or using a sequential prime generator with no upper bound resulted it massively longer run times. Bit of cheating? No, just using known information well!

(Yes, it was cheating)