patternpythonMinor
Project Euler Problem 10
Viewed 0 times
problemprojecteuler
Problem
Project Euler problem 10 is to find the sum of all primes less than 2 million. I have written a program that does this, and it works, but it takes an excruciatingly long amount of time. What I'm asking is if there is any way I could optimize this to make it run much faster.
I wrote it in an app on my iPad called Pythonista.
I wrote it in an app on my iPad called Pythonista.
def checkPrime(number):
if number == 2:
return True
if number < 2:
return False
if number % 2 == 0:
return False
for i in range(3, (number**1/2)-1, 2):
if number % i == 0:
return False
return True
primes = [i for i in range(10000) if checkPrime(i)]
print sum(primes)Solution
This problem can be solved much faster with a Sieve of Eratosthenes algorithm, especially since you need every prime between
However, there are a few optimizations you could make to your particular algorithm.
Dynamic Programming
Your code preforms some redundant calculations. For example, once you've checked if
2 and n for you to sum them up.However, there are a few optimizations you could make to your particular algorithm.
Dynamic Programming
Your code preforms some redundant calculations. For example, once you've checked if
n % 2 is zero, you know n % 4, n % 6... are also zero. To avoid these calculations you could instead divide by only the prime numbers up to and including √n:primes = [2] #define your array of prime numbers
def checkPrime(number):
if number number**0.5:
break; #no need to keep going
if number % p == 0:
return False
primes.append(number);
return True
primes = [i for i in range(10) if checkPrime(i)]
print sum(primes)Code Snippets
primes = [2] #define your array of prime numbers
def checkPrime(number):
if number < primes[0]:
return False
for p in primes: #only iterate through the primes
if p > number**0.5:
break; #no need to keep going
if number % p == 0:
return False
primes.append(number);
return True
primes = [i for i in range(10) if checkPrime(i)]
print sum(primes)Context
StackExchange Code Review Q#126347, answer score: 3
Revisions (0)
No revisions yet.