Skip to content

Instantly share code, notes, and snippets.

@dcbriccetti
Created July 3, 2015 21:00
Show Gist options
  • Save dcbriccetti/3fe745947e9988e96918 to your computer and use it in GitHub Desktop.
Save dcbriccetti/3fe745947e9988e96918 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes is faster with list than with numpy.array
import math
import numpy
from timeit import timeit
HIGHEST = 100000
ARRAY_LEN = HIGHEST + 1 # For 0
def make_sieve():
sieve = numpy.ones(ARRAY_LEN)
mark_composites(sieve)
return sieve
def make_sieve_list():
sieve = []
for n in range(ARRAY_LEN): sieve.append(True)
mark_composites(sieve)
return sieve
def mark_composites(sieve):
for prime in range(2, int(math.sqrt(HIGHEST)) + 1):
for n in range(prime * 2, ARRAY_LEN, prime):
sieve[n] = False
reps = 1000
print(timeit(make_sieve_list, number=reps))
print(timeit(make_sieve, number=reps))
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 /Users/daveb/devel/python-lessons/Harder/sieve.py
36.04646955100179
49.208132846993976
Process finished with exit code 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment