Python sieve prime numbers -
i trying sum of prime numbers using sieve on python 2.7. when run program wind 0 everytime. have no idea why happening.
import math,time start=time.clock() def primesieve(limit): final=0 a=[true]*limit a[0]=a[1]=false i,isprime in enumerate(a): if isprime: n in xrange(i,limit,i): a[n]=false in xrange(limit): if a[i]: final=final+i return final print primesieve(2000000) elapsed=time.clock()-start print elapsed
for n in xrange(i,limit,i): a[n]=false
it should be:
for n in xrange(2*i,limit,i): a[n]=false
or, more efficiently:
for n in xrange(i*i,limit, 2*i): #assuming cleared numbers a[n]=false
because otherwise end setting i
non-prime, when prime. (the sieve should mark multiples of i
non-primes, except i
itself!)
note iterating on numbers, limit
, can safely stopped after reaching sqrt(limit)
:
import itertools def primesieve(limit): = [true] * limit a[0] = a[1] = false sqrt_limit = int(limit**0.5) + 1 predicate = lambda x: x[0] <= sqrt_limit i, isprime in it.takewhile(predicate, enumerate(a)): if isprime: n in xrange(i*i, limit, i): a[n] = false return sum(i i,n in enumerate(a) if n)
the takewhile
function stop iteration right after reaching square root of limit
. i*i
wont give errors since smaller limit
.
on machine twice fast iterating on numbers.
Comments
Post a Comment