I've written the erathostenes algorithm in python a few weeks ago, and it looked like the following:
def erathostenes(n):
A = range(2,n+1)
B = []
i = 0
while A[i] < math.sqrt(n):
B.append(A[i])
j = i
aux = A[i]
while j < len(A):
if A[j]%aux == 0:
A[j] = 0
j += aux
i += 1
while A[i] == 0:
i += 1
for i in range(len(A)):
if A[i] != 0:
B.append(A[i])
i += 1
return B
After thinking a little (I'm noob in programming) i just did some modifications in my algorithm an right now looks like:
def erathostenes(n):
A = range(2,n + 1)
B = []
i = 0
raiz = math.sqrt(n)
lenA = len(A)
rangeLenA = range(lenA)
while A[i] < raiz:
B.append(A[i])
j = i
aux = A[i]
while j < lenA:
A[j] = 0
j += aux
i += 1
while A[i] == 0:
i += 1
for i in rangeLenA:
if A[i] != 0:
B.append(A[i])
i += 1
return B
If I execute the algorithm with n=10.000.000 the execution time in the first code is approximately 7 sec and with the second code it's about 4 seconds.
Any ideas about some more optimizations in my algorithm? thanks!