Created
December 6, 2011 01:43
-
-
Save willtownes/1436308 to your computer and use it in GitHub Desktop.
Faster way to list primes in Python
This file contains hidden or 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
def listprimes2(m): | |
'''another attempt to list all primes below m''' | |
values = range(m+1) #note that in this list the key and the value are the same. | |
primes = values[:] | |
primes[1] = 0 #1 doesn't count as a prime | |
for i in values: | |
if primes[i] == 0: | |
pass | |
else: | |
for j in values[i+1:]: | |
if primes[j]==0 or primes[j]%i != 0: | |
pass | |
else: | |
primes[j] = 0 | |
return primes | |
import time | |
tstart = time.time() | |
ans = sum(listprimes2(2000000)) | |
telapsed = time.time()-tstart |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks John!