Project Euler problem 7

Source code available on GitHub.

A very succinct question:

  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?

Well, in problem 3 we already made a function `isPrime(number)` to check if a number is prime, so let’s port that right in:

import math

def isPrime(number):
    if number == 1:
        return False
    else:
        if number == 2:
            return True
        else:
            for i in range(2,math.ceil(math.sqrt(number))+1):
                if number % i == 0:
                    return False
            return True

Now we just want to keep going through all the positive integers, generating primes until we have 10,001 of them. This while loop will make an infinite list of primes if you leave it to go on for long enough:

primes = []

i = 1
while True:
    if isPrime(i):
        primes.append(i)
    i += 1

We just add a termination if len(primes) is above 10,001 and print off our 10,001st prime! This is the whole program

import math

def isPrime(number):
    if number == 1:
        return False
    else:
        if number == 2:
            return True
        else:
            for i in range(2,math.ceil(math.sqrt(number))+1):
                if number % i == 0:
                    return False
            return True

primes = []

i = 1
while True:
    if isPrime(i):
        primes.append(i)
    if len(primes) > 10001:
        break
    i += 1

print(primes[10000])

Leave a Reply

Your email address will not be published. Required fields are marked *