Created
January 26, 2011 18:22
-
-
Save velociraptors/797157 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import time | |
def euler_sieve(n): | |
# source: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes | |
# Create a candidate list within which non-primes will | |
# marked as None, noting that only candidates below | |
# sqrt(n) need be checked. | |
candidates = range(n+1) | |
fin = int(n**0.5) | |
# Loop over the candidates, marking out each multiple. | |
# If the current candidate is already checked off then | |
# continue to the next iteration. | |
for i in xrange(2, fin+1): | |
if not candidates[i]: | |
continue | |
candidates[2*i::i] = [None] * (n//i - 1) | |
# Filter out non-primes and return the list. | |
return [i for i in candidates[2:] if i] | |
def print_sieve_info(n): | |
start = time() | |
primes = euler_sieve(n) | |
stop = time() | |
print('n = {0}'.format(n)) | |
print('sum: {0}'.format(sum(primes))) | |
print('Final time: {0}'.format(stop-start)) | |
print_sieve_info(200) | |
print_sieve_info(200000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment