Here'sanaiveyetshortsieveoferatosthenesinpython.
Thisoneremovesthecompositesfromthelistinsitu
untiltherearenoneleftandonlyprimesremain.
Aflawisthatmanynumbersarecheckedmorethanonce.
a=list(range(2,1000))
forxina:
n=x
whilex*n<=max(a):
ifx*nina:
a.remove(x*n)
n+=1
print(a)
Howcanweeliminatetheredundancy?
Thenextoneitriedusesaslightlydifferentapproach,
usingtwolists, oneofcompositeswhichispopulatedinthefirstloop
andoneoftheprimeswhichareeveryintegernotinthecomposites,
populatedinthesecondloop.
comp=[]
forainrange(2,1000):
ifanotincomp:
n=a
whilen*a<=1000:
comp.append(n*a)
n+=1
primes=[]
forcinrange(2,1000):
ifcnotincomp:
primes.append(c)
print(primes)
butthis following one belowis evenbettersinceitseems to avoidanyrepetition.
Foreachstartingfactoratemporarylistofcompositesisgenerated,
thesearethenremovedfromtheprimeslist,
andthenthelogicmovestothenextprimefactorinthelist
andrepeatsthesameprocessuntilitsdone.
a=list(range(2,1000))
forxina:
comp=[]
foryina:
comp.append(x*y)
forzincomp:
ifzina:
a.remove(z)
print(a)
aha! but there was redundancy in this onetoo.the first ungoverned complex is n*n, but we were enumerating n*2, n*3, n*5 etc up to n*n, this can be amend. Likewise we take to avoid checking the Numbers when they are overlargely, so here is our concluding version, by far the most elegant in my perspective.
a=list(range(2,1000))
forxina:
comp=[]
foryinrange(a.index(x),len(a)):
q=x*a[y]
ifq<=max(a):
comp.append(q)
else:
break
forzincomp:
a.remove(z)
print(a)
when you optimize codification like this it gets more scalable, for a big input the lag maked by inefficiencies is minimised. Too it is more esthetic, make n't utilize a sleigh cock to break a walnut!
Related posts:
Download the Complete Angels and Demons Discourse Series
Sec POSSO PROMETER MAIS Bash MESMO.
What is the one point you ca n't populate without?