Today I solved a problem given in Project Euler, it's problem number 10 and it took 7 hrs for my python program to show the result. But in that forum itself a person named lassevk posted solution for this and it took only 4 sec. And its not possible for me to post this question in that forum because its not a discussion forum. So, think about this if you want to mark this question as non-constructive.
marked = [0] * 2000000
value = 3
s = 2
while value < 2000000:
if marked[value] == 0:
s += value
i = value
while i < 2000000:
marked[i] = 1
i += value
value += 2
print s
If anyone understands this code please explain it as simple as possible.
This is my code which took 7 hrs to compute (I think I also used the same logic of Sieve of Eratosthenes technique which was mentioned in answers below):
import time
start = time.clock()
total = 0
limit = 2000000
KnownPrime = set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71])
KnownPrime.update(set([73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
131, 137, 139, 149, 151, 157, 163, 167, 173]))
suspected = set(range(2, limit+1)) # list of suspected prime numbers
for p in KnownPrime:
if p <= limit:
total += p
suspected.difference_update(set(range(p, limit+1, p)))
for i in suspected:
k = i/2
if k % 2 == 0: k += 1
PrimeCheck = set(range(k, 2, -2))
PrimeCheck.difference_update(KnownPrime)
for j in PrimeCheck:
if i % j == 0:
break
if i % j:
total += i
print time.clock() - start
print total
So, can anyone tell me why did it took that much time.
Finally I did it here's my refactored code. Now it can show result with in 2 sec.
import math
import __builtin__
sum = __builtin__.sum
def is_prime(num):
if num < 2: return False
if num == 2: return True
if num % 2 == 0: return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0: return False
return True
def sum_prime(num):
if num < 2: return 0
sum_p = 2
core_primes = []
suspected = set(range(3, num + 1, 2))
for i in range(3, int(math.sqrt(num)) + 1, 2):
if is_prime(i): core_primes.append(i)
for p in core_primes:
sum_p += p
suspected.difference_update(set(range(p, num + 1, p)))
return sum(suspected) + sum_p
print sum_prime(2000000)
And here is the visualization for that.