Project Euler problem 10

Source code available on GitHub.

Another prime-related problem:

  The sum of the primes below 10 is \(2 + 3 + 5 + 7 = 17\).  Find the sum of all the primes below two million.

From problem 7 we already have a nice function to check if a number is prime or not:

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

That means all we need to do is keep checking every number, add any primes to a big list, and stop before we hit 2 million.

def sumOfPrimes(N): # Sum of all primes below N
    sum = 0
    for i in range(1,N+1,2):
        if isPrime(i):
            sum += i
    return sum

This code does just that. I’ve told the range() function to only return odd numbers because, well – no primes are even except for 2. For that reason I’ve started with my sum as 2 and initiated the for loop starting with i = 3.

That’s our solution done!

import math

def isPrime(number):
    prime = True #Assume prime
    if number == 1:
        return False
    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

def sumOfPrimes(N): # Sum of all primes below N
    sum = 2
    for i in range(3,N+1,2):
        if isPrime(i):
            sum += i
    return sum

print(sumOfPrimes(2000000))

 

Leave a Reply

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