Skip to content

Instantly share code, notes, and snippets.

@underhilllabs
Created April 21, 2012 06:40
Show Gist options
  • Save underhilllabs/2434851 to your computer and use it in GitHub Desktop.
Save underhilllabs/2434851 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
def sieve(MAX):
# list of primes
primes = []
# list of all numbers, non-primes will be slowly zeroed out
nums = []
# start with first prime
prime = 2
# populate list from 0 to MAX
nums = [i for i in range(MAX+1)]
# zero out 1, non-prime
nums[1] = 0
# start sieving
while prime <= MAX:
# continue loop, if this number has already been zeroed out
if nums[prime] == 0:
prime += 1
continue
# not zeroed out, so a prime!
# So append to primes list
primes.append(prime)
# pmult is multiple of prime
pmult = prime
while (pmult + prime) <= MAX:
# inc pmult by current prime
pmult += prime
# zero out multiple of current prime
nums[pmult] = 0
prime += 1
return primes
# Project Euler problem 10
p = []
m = 1999999
p = sieve(m)
print "number of primes less than", m, ":", len(p)
print sum(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment