I don't understand what is taking the program so long:
#!/bin/python
primes=[]
i=0
j=0
k=0
for i in range(2,2000000): #fill in the list
primes.append(i)
i=0
while i<len(primes):
j=primes[i]
print(j)
k=0
while j*(j+k)<primes[len(primes)-1]: ##referred as 'line A'
try:
primes.remove(j*(j+k))
except ValueError:
k=k+1
continue
k=k+1
i=i+1
sump=0
i=0
for i in range(len(primes)):
sump=sump+primes[i]
print(sump)
I understand why the overall code is very inefficient, but line A takes 2 hours for j=2
, and I don't understand why that is. Surely the list.remove(x)
method is very inefficient?
primes = list(range(2,2000000))
,primes[len(primes)-1]
isprimes[-1]
and the last for loop issump = sum(primes)
. I don't think that's your problem, but it's a start. \$\endgroup\$primes = [x for x in primes if x % j or x == j]
. Even creating a completely new list each loop, this is orders of magnitude faster \$\endgroup\$list.remove
is an O(n) operation; first it needs to search through the list to find the item, then move all of the items after it in the list one spot to the left. Using a set would be much more efficient. \$\endgroup\$