Skip to content

Instantly share code, notes, and snippets.

@sj26
Created February 21, 2011 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sj26/836755 to your computer and use it in GitHub Desktop.
Save sj26/836755 to your computer and use it in GitHub Desktop.
The fastest way I could implement Erastothenes prime number sieve in Python.
import sys, collections
cases = int(sys.stdin.readline().strip())
for case in range(1, cases + 1):
candidate_min, candidate_max = map(int, sys.stdin.readline().strip().split())
# Python is good at sparse dictionaries, so use a bubbling
# Sieve of Erastothenes to be memory efficient and fairly
# computationally efficient
composites = collections.defaultdict(list)
for candidate in range(2, candidate_max + 1):
if candidate not in composites:
# This candidate is prime!
# Print it if we should
if candidate >= candidate_min:
print(candidate)
# Find the first composite of this prime.
composites[candidate * candidate] = [candidate]
else:
# This candidate is a composite.
# Find the next multiple of each prime which found this composite.
for prime in composites[candidate]:
composites[prime + candidate].append(prime)
# We don't care about this candidate any more.
del composites[candidate]
print()
@sj26
Copy link
Author

sj26 commented Feb 21, 2011

... but it's still not fast enough. :-(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment