Username
Password
login
register
Tweet
new code
recent codes
news
samples
help
about
FAQ
API
Computer geeks!
RecruitCoders.com
choose language
Ada
Assembler
Assembler
AWK (gawk)
AWK (mawk)
Bash
bc
Brainf**k
C
C#
C++
C++0x
C99 strict
CLIPS
Clojure
COBOL
COBOL 85
Common Lisp (clisp)
D (dmd)
Erlang
F#
Factor
Falcon
Forth
Fortran
Go
Groovy
Haskell
Icon
Intercal
Java
Java7
JavaScript (rhino)
JavaScript (spidermonkey)
Lua
Nemerle
Nice
Nimrod
Objective-C
Ocaml
Oz
Pascal (fpc)
Pascal (gpc)
Perl
Perl 6
PHP
Pike
Prolog (gnu)
Prolog (swi)
Python
Python 3
R
Ruby
Scala
Scheme (guile)
Smalltalk
SQL
Tcl
Text
Unlambda
VB.NET
Whitespace
run code
private
5s
15s
enter your source code
or
insert
template
or
sample
or
your template
Would you like to manage your submissions?
Sign up
now.
"""Compare performance of differenct Sieve of Eratosthenes implementations.""" #NOTE: maintain single source 2.5-x and 3.x compatibility # if `numpy`/`gmpy2` is installed test it import collections, itertools, sys import timeit try: range = xrange map = itertools.imap filter = itertools.ifilter except NameError: pass def print25(*args, **kwargs): # `from __future__ import print_function` doesn't work on Python # <= 2.5 sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') file = kwargs.get('file', sys.stdout) file.write(sep.join(map(str, args))) file.write(end) def profile(func): return func if '--profile' in sys.argv: try: from profilestats import profile # pip install profilestats except ImportError: pass def register(func): register.functions.append(func) return func register.functions = [] def tag(*tags): def decorator(func): func.tags = getattr(func, 'tags', set()) func.tags.update(tags) return register(func) return decorator # http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Using_generator @tag('pure') def iprimes_upto(limit): is_prime = [False] * 2 + [True] * (limit - 1) for n in range(limit + 1): if is_prime[n]: yield n for i in range(n*n, limit+1, n): # start at ``n`` squared is_prime[i] = False @tag('pure') def iprimes_upto_enumerate(limit): is_prime = [False] * 2 + [True] * (limit - 1) for n, p in enumerate(is_prime): if p: yield n for i in range(n*n, limit+1, n): # start at ``n`` squared is_prime[i] = False try: import math import numpy @tag('sequence', 'numpy') def nolfonzo_prime6(upto): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3638617#3638617 primes=numpy.arange(3,upto+1,2) isprime=numpy.ones((upto-1)/2,dtype=bool) for factor in primes[:int(math.sqrt(upto))]: if isprime[(factor-2)/2]: isprime[(factor*3-2)/2:(upto-1)/2:factor]=0 return numpy.insert(primes[isprime],0,2) # http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Using_numpy import numpy @tag('sequence', 'numpy') def primes_upto2(limit): is_prime = numpy.ones(limit + 1, dtype=numpy.bool) for n in xrange(2, int(limit**0.5 + 1.5)): if is_prime[n]: is_prime[n*n::n] = 0 return numpy.nonzero(is_prime)[0][2:] @tag('sequence', 'numpy') def primes_upto4(limit): is_prime = numpy.ones(limit + 1, dtype=numpy.bool) for n in xrange(3, int(limit**0.5 + 1.5), 2): if is_prime[n]: is_prime[n*n::2*n] = 0 is_prime[:2] = is_prime[4::2] = 0 return is_prime.nonzero()[0] @tag('numpy') def primes_upto4_gen(limit): is_prime = numpy.ones(limit + 1, dtype=numpy.bool) for n in xrange(3, int(limit**0.5 + 1.5), 2): if is_prime[n]: is_prime[n*n::2*n] = 0 yield 2 for i, p in enumerate(is_prime[3::2]): if p: yield 3 + 2*i @tag('numpy') def primes_upto2_gen(limit): is_prime = numpy.ones(limit + 1, dtype=numpy.bool) for n in xrange(2, int(limit**0.5 + 1.5)): if is_prime[n]: is_prime[n*n::n] = 0 return (i for i in xrange(2, limit+1) if is_prime[i]) @tag('numpy') def primes_upto2_gen2(limit): """Generate prime numbers less than limit. Assume limit > 2 """ yield 2 is_prime = numpy.ones(limit, dtype=numpy.bool) for n in xrange(3, int(limit**.5)+1, 2): if is_prime[n]: yield n is_prime[n*n::n] = False for n in xrange(n+2, limit, 2): if is_prime[n]: yield n @tag('numpy') def primes_upto2_gen3(limit): """Generate prime numbers less than limit. Assume limit > 2 """ yield 2 is_prime = numpy.ones(limit, dtype=numpy.bool) for n in xrange(3, int(limit**.5)+1, 2): if is_prime[n]: yield n is_prime[n*n::2*n] = False for n in xrange(n+2, limit, 2): if is_prime[n]: yield n from numpy import array, bool_, multiply, nonzero, ones, put, resize # def makepattern(smallprimes): pattern = ones(multiply.reduce(smallprimes), dtype=bool_) pattern[0] = 0 for p in smallprimes: pattern[p::p] = 0 return pattern # @tag('sequence', 'numpy') def primes_upto3(limit, smallprimes=(2,3,5,7,11)): sp = array(smallprimes) if limit <= sp.max(): return sp[sp <= limit] # isprime = resize(makepattern(sp), limit + 1) isprime[:2] = 0; put(isprime, sp, 1) # for n in range(sp.max() + 2, int(limit**0.5 + 1.5), 2): if isprime[n]: isprime[n*n::n] = 0 return nonzero(isprime)[0] @tag('sequence', 'numpy') def primesfrom3to(n): """ Returns a array of primes, 3 <= p < n """ # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 sieve = numpy.ones(n/2, dtype=numpy.bool) for i in xrange(3,int(n**0.5)+1,2): if sieve[i/2]: sieve[i*i/2::i] = False return numpy.r_[2,2*numpy.nonzero(sieve)[0][1::]+1] @tag('sequence', 'numpy') def primesfrom2to(n): """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = numpy.ones(n/3+((n+1)&1)*(n%3)/2, dtype=numpy.bool) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1+(i&1) sieve[ ((k*k)/3) ::2*k] = False sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False primes = 3*numpy.nonzero(sieve)[0]+1 primes += (primes+1)%2 return numpy.r_[2,3,primes] @tag('sequence', 'numpy') def primesfrom2to2(n): """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = numpy.ones(n/3+((n+1)&1)*(n%3)/2, dtype=numpy.bool) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1+(i&1) sieve[ ((k*k)/3) ::2*k] = False sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0]+1)|1)] @tag('sequence', 'numpy') def primesfrom2to3(n): """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = numpy.ones(n/3 + (n%6==2), dtype=numpy.bool) sieve[0] = False for i in xrange(int(n**0.5)/3+1): if sieve[i]: k=3*i+1|1 sieve[ ((k*k)/3) ::2*k] = False sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0]+1)|1)] @tag('numpy') def primesgen1(n): """ Generates all primes < n """ # http://stackoverflow.com/questions/2897297/speed-up-bitstring-bit-operations-in-python/2908512#2908512 sieve1 = numpy.ones(n/6+1, dtype=numpy.bool) sieve5 = numpy.ones(n/6 , dtype=numpy.bool) sieve1[0] = False yield 2; yield 3; for i in xrange(int(n**0.5)/6+1): if sieve1[i]: k=6*i+1; yield k; sieve1[ ((k*k)/6) ::k] = False sieve5[(k*k+4*k)/6::k] = False if sieve5[i]: k=6*i+5; yield k; sieve1[ ((k*k)/6) ::k] = False sieve5[(k*k+2*k)/6::k] = False for i in xrange(i+1,n/6): if sieve1[i]: yield 6*i+1 if sieve5[i]: yield 6*i+5 if 1 < n%6 <= 5: if sieve1[i+1]: yield 6*i+1 @tag('numpy') def primesgen2(n): # http://stackoverflow.com/questions/2897297/speed-up-bitstring-bit-operations-in-python/2908512#2908512 """ Input n>=30, Generates all primes < n """ sieve01 = numpy.ones(n/30+1, dtype=numpy.bool) sieve07 = numpy.ones(n/30+1, dtype=numpy.bool) sieve11 = numpy.ones(n/30+1, dtype=numpy.bool) sieve13 = numpy.ones(n/30+1, dtype=numpy.bool) sieve17 = numpy.ones(n/30+1, dtype=numpy.bool) sieve19 = numpy.ones(n/30+1, dtype=numpy.bool) sieve23 = numpy.ones(n/30+1, dtype=numpy.bool) sieve29 = numpy.ones(n/30 , dtype=numpy.bool) sieve01[0] = False yield 2; yield 3; yield 5; for i in xrange(int(n**0.5)/30+1): if sieve01[i]: k=30*i+1; yield k; sieve01[ (k*k)/30::k] = False sieve07[(k*k+ 6*k)/30::k] = False sieve11[(k*k+10*k)/30::k] = False sieve13[(k*k+12*k)/30::k] = False sieve17[(k*k+16*k)/30::k] = False sieve19[(k*k+18*k)/30::k] = False sieve23[(k*k+22*k)/30::k] = False sieve29[(k*k+28*k)/30::k] = False if sieve07[i]: k=30*i+7; yield k; sieve01[(k*k+ 6*k)/30::k] = False sieve07[(k*k+24*k)/30::k] = False sieve11[(k*k+16*k)/30::k] = False sieve13[(k*k+12*k)/30::k] = False sieve17[(k*k+ 4*k)/30::k] = False sieve19[ (k*k)/30::k] = False sieve23[(k*k+22*k)/30::k] = False sieve29[(k*k+10*k)/30::k] = False if sieve11[i]: k=30*i+11; yield k; sieve01[ (k*k)/30::k] = False sieve07[(k*k+ 6*k)/30::k] = False sieve11[(k*k+20*k)/30::k] = False sieve13[(k*k+12*k)/30::k] = False sieve17[(k*k+26*k)/30::k] = False sieve19[(k*k+18*k)/30::k] = False sieve23[(k*k+ 2*k)/30::k] = False sieve29[(k*k+ 8*k)/30::k] = False if sieve13[i]: k=30*i+13; yield k; sieve01[(k*k+24*k)/30::k] = False sieve07[(k*k+ 6*k)/30::k] = False sieve11[(k*k+ 4*k)/30::k] = False sieve13[(k*k+18*k)/30::k] = False sieve17[(k*k+16*k)/30::k] = False sieve19[ (k*k)/30::k] = False sieve23[(k*k+28*k)/30::k] = False sieve29[(k*k+10*k)/30::k] = False if sieve17[i]: k=30*i+17; yield k; sieve01[(k*k+ 6*k)/30::k] = False sieve07[(k*k+24*k)/30::k] = False sieve11[(k*k+26*k)/30::k] = False sieve13[(k*k+12*k)/30::k] = False sieve17[(k*k+14*k)/30::k] = False sieve19[ (k*k)/30::k] = False sieve23[(k*k+ 2*k)/30::k] = False sieve29[(k*k+20*k)/30::k] = False if sieve19[i]: k=30*i+19; yield k; sieve01[ (k*k)/30::k] = False sieve07[(k*k+24*k)/30::k] = False sieve11[(k*k+10*k)/30::k] = False sieve13[(k*k+18*k)/30::k] = False sieve17[(k*k+ 4*k)/30::k] = False sieve19[(k*k+12*k)/30::k] = False sieve23[(k*k+28*k)/30::k] = False sieve29[(k*k+22*k)/30::k] = False if sieve23[i]: k=30*i+23; yield k; sieve01[(k*k+24*k)/30::k] = False sieve07[(k*k+ 6*k)/30::k] = False sieve11[(k*k+14*k)/30::k] = False sieve13[(k*k+18*k)/30::k] = False sieve17[(k*k+26*k)/30::k] = False sieve19[ (k*k)/30::k] = False sieve23[(k*k+ 8*k)/30::k] = False sieve29[(k*k+20*k)/30::k] = False if sieve29[i]: k=30*i+29; yield k; sieve01[ (k*k)/30::k] = False sieve07[(k*k+24*k)/30::k] = False sieve11[(k*k+20*k)/30::k] = False sieve13[(k*k+18*k)/30::k] = False sieve17[(k*k+14*k)/30::k] = False sieve19[(k*k+12*k)/30::k] = False sieve23[(k*k+ 8*k)/30::k] = False sieve29[(k*k+ 2*k)/30::k] = False for i in xrange(i+1,n/30): if sieve01[i]: yield 30*i+1 if sieve07[i]: yield 30*i+7 if sieve11[i]: yield 30*i+11 if sieve13[i]: yield 30*i+13 if sieve17[i]: yield 30*i+17 if sieve19[i]: yield 30*i+19 if sieve23[i]: yield 30*i+23 if sieve29[i]: yield 30*i+29 if n%30 > 1: if sieve01[i+1]: yield 30*i+1 if n%30 > 7: if sieve07[i+1]: yield 30*i+7 if n%30 > 11: if sieve11[i+1]: yield 30*i+11 if n%30 > 13: if sieve13[i+1]: yield 30*i+13 if n%30 > 17: if sieve17[i+1]: yield 30*i+17 if n%30 > 19: if sieve19[i+1]: yield 30*i+19 if n%30 > 23: if sieve23[i+1]: yield 30*i+23 except ImportError: pass #http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 @tag('pure', 'sequence') def primes1(n): """ Returns a list of primes < n """ sieve = [True] * (n//2) for i in range(3,int(n**0.5)+1,2): if sieve[i//2]: sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1) return [2] + [2*i+1 for i in range(1,n//2) if sieve[i]] @tag('pure', 'sequence') def primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,n,2) if sieve[i]] try: #http://stackoverflow.com/questions/2897297/speed-up-bitstring-bit-operations-in-python/2901856#2901856 import gmpy2 @tag('gmpy2') def prime_numbers(limit=1000000): '''Prime number generator. Yields the series 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ... using Sieve of Eratosthenes. ''' yield 2 sub_limit = int(limit**0.5) # Actual number is 2*bit_position + 1. oddnums = gmpy2.xmpz(1) current = 0 while True: current += 1 current = oddnums.bit_scan0(current) prime = 2 * current + 1 if prime > limit: break yield prime # Exclude further multiples of the current prime number if prime <= sub_limit: for j in range(2*current*(current+1), limit>>1, prime): oddnums.bit_set(j) @tag('gmpy2') def prime_numbers2(limit=1000000): '''Prime number generator. Yields the series 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ... using Sieve of Eratosthenes. ''' yield 2 sub_limit = int(limit**0.5) # Actual number is 2*bit_position + 1. oddnums = gmpy2.xmpz(1) f_set = oddnums.bit_set f_scan0 = oddnums.bit_scan0 current = 0 while True: current += 1 current = f_scan0(current) prime = 2 * current + 1 if prime > limit: break yield prime # Exclude further multiples of the current prime number if prime <= sub_limit: consume(map(f_set,range(2*current*(current+1), limit>>1, prime))) @tag('gmpy2') def prime_numbers4(limit=1000000): '''Prime number generator. Yields the series 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ... using Sieve of Eratosthenes. ''' sub_limit = int(limit**0.5) flags = gmpy2.xmpz(1) flags[(limit>>1)+1] = True f_scan0 = flags.bit_scan0 current = 0 prime = 2 while prime <= sub_limit: yield prime current += 1 current = f_scan0(current) prime = 2 * current + 1 flags[2*current*(current+1):limit>>1:prime] = True while prime <= limit: yield prime current += 1 current = f_scan0(current) prime = 2 * current + 1 # @tag('gmpy2') def gmpy_next_prime_primes(limit): next_ = gmpy2.next_prime p = next_(1) while p < limit: yield p p = next_(p) except ImportError: pass ############################################################################### #http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/2068548#2068548 from math import sqrt, ceil try: import builtins except ImportError: import __builtin__ as builtins # small primes array __smallp = ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997) @tag('pure', 'sequence') def sieve_wheel_30(N): # http://zerovolt.com/?p=88 ''' Returns a list of primes <= N using wheel criterion 2*3*5 = 30 Copyright 2009 by zerovolt.com This code is free for non-commercial purposes, in which case you can just leave this comment as a credit for my work. If you need this code for commercial purposes, please contact me by sending an email to: info [at] zerovolt [dot] com.''' wheel = (2, 3, 5) const = 30 if N < 2: return [] if N <= const: pos = 0 while __smallp[pos] <= N: pos += 1 return list(__smallp[:pos]) # make the offsets list offsets = (7, 11, 13, 17, 19, 23, 29, 1) # prepare the list p = [2, 3, 5] dim = 2 + N // const tk1 = [True] * dim tk7 = [True] * dim tk11 = [True] * dim tk13 = [True] * dim tk17 = [True] * dim tk19 = [True] * dim tk23 = [True] * dim tk29 = [True] * dim tk1[0] = False # help dictionary d # d[a , b] = c ==> if I want to find the smallest useful multiple of (30*pos)+a # on tkc, then I need the index given by the product of [(30*pos)+a][(30*pos)+b] # in general. If b < a, I need [(30*pos)+a][(30*(pos+1))+b] d = {} for x in offsets: for y in offsets: res = (x*y) % const if res in offsets: d[(x, res)] = y # another help dictionary: gives tkx calling tmptk[x] tmptk = {1:tk1, 7:tk7, 11:tk11, 13:tk13, 17:tk17, 19:tk19, 23:tk23, 29:tk29} pos, prime, lastadded, stop = 0, 0, 0, int(ceil(sqrt(N))) # inner functions definition def del_mult(tk, start, step): for k in range(start, len(tk), step): tk[k] = False # end of inner functions definition cpos = const * pos while prime < stop: # 30k + 7 if tk7[pos]: prime = cpos + 7 p.append(prime) lastadded = 7 for off in offsets: tmp = d[(7, off)] start = (pos + prime) if off == 7 else (prime * (const * (pos + 1 if tmp < 7 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 11 if tk11[pos]: prime = cpos + 11 p.append(prime) lastadded = 11 for off in offsets: tmp = d[(11, off)] start = (pos + prime) if off == 11 else (prime * (const * (pos + 1 if tmp < 11 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 13 if tk13[pos]: prime = cpos + 13 p.append(prime) lastadded = 13 for off in offsets: tmp = d[(13, off)] start = (pos + prime) if off == 13 else (prime * (const * (pos + 1 if tmp < 13 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 17 if tk17[pos]: prime = cpos + 17 p.append(prime) lastadded = 17 for off in offsets: tmp = d[(17, off)] start = (pos + prime) if off == 17 else (prime * (const * (pos + 1 if tmp < 17 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 19 if tk19[pos]: prime = cpos + 19 p.append(prime) lastadded = 19 for off in offsets: tmp = d[(19, off)] start = (pos + prime) if off == 19 else (prime * (const * (pos + 1 if tmp < 19 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 23 if tk23[pos]: prime = cpos + 23 p.append(prime) lastadded = 23 for off in offsets: tmp = d[(23, off)] start = (pos + prime) if off == 23 else (prime * (const * (pos + 1 if tmp < 23 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # 30k + 29 if tk29[pos]: prime = cpos + 29 p.append(prime) lastadded = 29 for off in offsets: tmp = d[(29, off)] start = (pos + prime) if off == 29 else (prime * (const * (pos + 1 if tmp < 29 else 0) + tmp) )//const del_mult(tmptk[off], start, prime) # now we go back to top tk1, so we need to increase pos by 1 pos += 1 cpos = const * pos # 30k + 1 if tk1[pos]: prime = cpos + 1 p.append(prime) lastadded = 1 for off in offsets: tmp = d[(1, off)] start = (pos + prime) if off == 1 else (prime * (const * pos + tmp) )//const del_mult(tmptk[off], start, prime) # time to add remaining primes # if lastadded == 1, remove last element and start adding them from tk1 # this way we don't need an "if" within the last while if lastadded == 1: p.pop() # now complete for every other possible prime while pos < len(tk1): cpos = const * pos if tk1[pos]: p.append(cpos + 1) if tk7[pos]: p.append(cpos + 7) if tk11[pos]: p.append(cpos + 11) if tk13[pos]: p.append(cpos + 13) if tk17[pos]: p.append(cpos + 17) if tk19[pos]: p.append(cpos + 19) if tk23[pos]: p.append(cpos + 23) if tk29[pos]: p.append(cpos + 29) pos += 1 # remove exceeding if present pos = len(p) - 1 while p[pos] > N: pos -= 1 if pos < len(p) - 1: del p[pos+1:] # return p list return p @tag('pure', 'sequence') def sieveOfEratosthenes(n): """sieveOfEratosthenes(n): return the list of the primes < n.""" # Code from: <dickinsm@gmail.com>, Nov 30 2006 # http://groups.google.com/group/comp.lang.python/msg/f1f10ced88c68c2d if n <= 2: return [] sieve = range(3, n, 2) if type(sieve) != list: sieve = list(sieve) top = len(sieve) for si in sieve: if si: bottom = (si*si - 3) // 2 if bottom >= top: break sieve[bottom::si] = [0] * -((bottom - top) // si) return [2] + [el for el in sieve if el] @tag('pure', 'sequence') def sieveOfAtkin(end): """sieveOfAtkin(end): return a list of all the prime numbers <end using the Sieve of Atkin.""" # Code by Steve Krenzel, <Sgk284@gmail.com>, improved # Code: http://krenzel.info/?p=83 # Info: http://en.wikipedia.org/wiki/Sieve_of_Atkin assert end > 0, "end must be >0" lng = ((end-1) // 2) sieve = [False] * (lng + 1) x_max, x2, xd = int(sqrt((end-1)/4.0)), 0, 4 for xd in range(4, 8*x_max + 2, 8): x2 += xd y_max = int(sqrt(end-x2)) n, n_diff = x2 + y_max*y_max, (y_max << 1) - 1 if not (n & 1): n -= n_diff n_diff -= 2 for d in range((n_diff - 1) << 1, -1, -8): m = n % 12 if m == 1 or m == 5: m = n >> 1 sieve[m] = not sieve[m] n -= d x_max, x2, xd = int(sqrt((end-1) / 3.0)), 0, 3 for xd in range(3, 6 * x_max + 2, 6): x2 += xd y_max = int(sqrt(end-x2)) n, n_diff = x2 + y_max*y_max, (y_max << 1) - 1 if not(n & 1): n -= n_diff n_diff -= 2 for d in range((n_diff - 1) << 1, -1, -8): if n % 12 == 7: m = n >> 1 sieve[m] = not sieve[m] n -= d x_max, y_min, x2, xd = int((2 + sqrt(4-8*(1-end)))/4), -1, 0, 3 for x in range(1, x_max + 1): x2 += xd xd += 6 if x2 >= end: y_min = (((int(ceil(sqrt(x2 - end))) - 1) << 1) - 2) << 1 n, n_diff = ((x*x + x) << 1) - 1, (((x-1) << 1) - 2) << 1 for d in range(n_diff, y_min, -8): if n % 12 == 11: m = n >> 1 sieve[m] = not sieve[m] n += d primes = [2, 3] if end <= 3: return primes[:max(0,end-2)] for n in range(5 >> 1, (int(sqrt(end))+1) >> 1): if sieve[n]: primes.append((n << 1) + 1) aux = (n << 1) + 1 aux *= aux for k in range(aux, end, 2 * aux): sieve[k >> 1] = False s = int(sqrt(end)) + 1 if s % 2 == 0: s += 1 primes.extend([i for i in range(s, end, 2) if sieve[i >> 1]]) return primes try: import numpy as np @tag('sequence', 'numpy') def ambi_sieve(n): # http://tommih.blogspot.com/2009/04/fast-prime-number-generator.html s = np.arange(3, n, 2) for m in builtins.xrange(3, int(n ** 0.5)+1, 2): if s[(m-3)/2]: s[(m*m-3)/2::m]=0 return np.r_[2, s[s>0]] except ImportError: pass @tag('pure', 'sequence') def ambi_sieve_plain(n): s = list(range(3, n, 2)) for m in range(3, int(n**0.5)+1, 2): if s[(m-3)//2]: for t in range((m*m-3)//2,(n>>1)-1,m): s[t]=0 return [2]+[t for t in s if t>0] @tag('pure', 'sequence') def sundaram3(max_n): numbers = list(range(3, max_n+1, 2)) half = (max_n)//2 initial = 4 for step in range(3, max_n+1, 2): for i in range(initial, half, step): numbers[i-1] = 0 initial += 2*(step+1) if initial > half: return [2] + [n for n in numbers if n] ############################################################################### @tag('pure', 'sequence') def rwh_primes2(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a list of primes, 2 <= p < n """ n, correction = n-n%6+6, 2-(n%6>1) sieve = [True] * (n//3) for i in range(1,int(n**0.5)//3+1): if sieve[i]: k=3*i+1|1 sieve[ k*k//3 ::2*k] = [False] * ((n//6-k*k//6-1)//k+1) sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1) return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]] @tag('pure', 'sequence') def sieveOfErat_Noldorin(end): # http://stackoverflow.com/questions/1023768/sieve-of-atkin-explanation/1023777#1023777 if end < 2: return [] #The array doesn't need to include even numbers lng = ((end//2)-1+end%2) # Create array and assume all numbers in array are prime sieve = [True]*(lng+1) # In the following code, you're going to see some funky # bit shifting and stuff, this is just transforming i and j # so that they represent the proper elements in the array. # The transforming is not optimal, and the number of # operations involved can be reduced. # Only go up to square root of the end for i in range(int(sqrt(end)) >> 1): # Skip numbers that aren't marked as prime if not sieve[i]: continue # Unmark all multiples of i, starting at i**2 for j in range( (i*(i + 3) << 1) + 3, lng, (i << 1) + 3): sieve[j] = False # Don't forget 2! primes = [2] # Gather all the primes into a list, leaving out the composite numbers primes.extend([(i << 1) + 3 for i in range(lng) if sieve[i]]) return primes try: import primegen # http://cr.yp.to/primegen.html @tag('primegen') def primegen_upto(n): pg = primegen.primegen() primegen.primegen_init(pg) next_ = primegen.primegen_next p = next_(pg) while p < n: yield p p = next_(pg) except ImportError: pass @tag('pure') def eratosthenes_dugres(n): # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3328618#3328618 N=list(range(n+1)) z=[0]*(n//2) for i in range(2, int(n**.5)+1): if N[i]: N[i*i::i] = z[:(n//i)-i+1] return filter(None, N[2:]) try: bytearray # `bytearray` is not present in pypy @tag('pure') def prime_pure(limit=1000000): # http://stackoverflow.com/questions/2897297/speed-up-bitstring-bit-operations-in-python/2897459#2897459 yield 2 flags = bytearray((limit + 7) // 8) sub_limit = int(limit**0.5) for i in range(3, limit, 2): byte, bit = divmod(i, 8) if not flags[byte] & (128 >> bit): yield i if i <= sub_limit: for j in range(i*3, limit, i*2): byte, bit = divmod(j, 8) flags[byte] |= (128 >> bit) except NameError: pass # ################################################################################ def consume(iterator): collections.deque(iterator, maxlen=0) @profile def test(n=1000000): nsmall = 10000 result = list(register.functions[0](nsmall)) for f in register.functions[1:]: for expected, got in zip(result, f(nsmall)): assert expected == got, (expected, got, f.__name__) results = [test_func(f, n, quiet=True) for f in register.functions] results.sort(key=lambda x:x[1]) for r in results: print25('%s:%s %s' % ( str(r[0]).ljust(25), ('%d ms' % (int(r[1]*1e3+0.5),)).rjust(10), r[2])) def test_func(f, n=1000000, quiet=False, repeat=3, ntimes=10): stmt = '%s(%d)' % (f.__name__, n) setup = 'from %s import %s' % (__name__, f.__name__) if not 'sequence' in f.tags: stmt = 'consume(%s)' % (stmt,) setup += '; from %s import consume' % (__name__,) t = timeit.Timer(stmt, setup) try: results = [r/ntimes for r in t.repeat(repeat=repeat, number=ntimes)] except Exception: time = -1 else: time = min(results) result = (f.__name__, time, ':'.join(f.tags)) if not quiet: print25(*result) return result if __name__=="__main__": test() try: for f in [primesgen2, primesfrom2to3]: test_func(f, n=10**9, repeat=1, ntimes=1) except NameError: pass # Python2.6 n=1e6 # primesfrom2to3 : 7 ms numpy:sequence # primesfrom2to2 : 7 ms numpy:sequence # ambi_sieve : 9 ms numpy:sequence # primesfrom2to : 9 ms numpy:sequence # primesfrom3to : 9 ms numpy:sequence # nolfonzo_prime6 : 12 ms numpy:sequence # primes_upto4 : 15 ms numpy:sequence # primes_upto3 : 15 ms numpy:sequence # primes_upto2 : 17 ms numpy:sequence # primegen_upto : 31 ms primegen # prime_numbers4 : 32 ms gmpy2 # primesgen2 : 35 ms numpy # primesgen1 : 38 ms numpy # rwh_primes2 : 44 ms pure:sequence # primes_upto2_gen3 : 47 ms numpy # primes_upto2_gen2 : 48 ms numpy # primes1 : 49 ms pure:sequence # primes : 50 ms pure:sequence # primes_upto4_gen : 53 ms numpy # sieve_wheel_30 : 56 ms pure:sequence # sieveOfEratosthenes : 79 ms pure:sequence # prime_numbers2 : 83 ms gmpy2 # primes_upto2_gen : 91 ms numpy # sieveOfErat_Noldorin : 112 ms pure:sequence # ambi_sieve_plain : 145 ms pure:sequence # prime_numbers : 146 ms gmpy2 # eratosthenes_dugres : 161 ms pure # sieveOfAtkin : 219 ms pure:sequence # sundaram3 : 235 ms pure:sequence # iprimes_upto : 281 ms pure # iprimes_upto_enumerate : 283 ms pure # prime_pure : 605 ms pure # Python2.6 n=1e9 # primesgen1 35.7735440731 numpy # primesgen2 27.4978778362 numpy # primesfrom2to3 9.91236019135 numpy:sequence # Python3 n=1e6 # prime_numbers4 : 32 ms gmpy2 # rwh_primes2 : 38 ms pure:sequence # sieve_wheel_30 : 44 ms pure:sequence # primes : 48 ms pure:sequence # primes1 : 49 ms pure:sequence # sieveOfEratosthenes : 49 ms pure:sequence # prime_numbers2 : 92 ms gmpy2 # sieveOfErat_Noldorin : 93 ms pure:sequence # ambi_sieve_plain : 109 ms pure:sequence # prime_numbers : 112 ms gmpy2 # eratosthenes_dugres : 112 ms pure # sundaram3 : 187 ms pure:sequence # sieveOfAtkin : 199 ms pure:sequence # iprimes_upto_enumerate : 225 ms pure # iprimes_upto : 227 ms pure # prime_pure : 500 ms pure # pypy n=1e6 # rwh_primes2 : 84 ms pure:sequence # sieve_wheel_30 : 113 ms pure:sequence # primes : 115 ms pure:sequence # primes1 : 116 ms pure:sequence # sieveOfEratosthenes : 135 ms pure:sequence # sieveOfErat_Noldorin : 251 ms pure:sequence # ambi_sieve_plain : 252 ms pure:sequence # sieveOfAtkin : 347 ms pure:sequence # sundaram3 : 436 ms pure:sequence
click here to enter input (stdin) or additional note
syntax highlight
What is ideone?
Ideone is something more than a pastebin; it's an online compiler and debugging tool which allows
to compile and run code online in more than 40 programming languages.
How to use ideone?
Choose a programming language, enter your source code and input data into text boxes. Then check or uncheck
run code
(whether to execute your program) and
private
(whether not to list your code in the
recent codes
page) checkboxes, click the submit button and watch your snippet being executed.
Having problems?
Check the
samples
to see how to write a properly working code. To find out more, see the
help
section or the
FAQ
page.
enter your input (stdin)
enter your note
This web site requires JavaScript
Choose your language:
English
Hindi
Hungarian
Mongolian
Polish
Russian
Spanish
Traditional Chinese
Help us translate Ideone -
click here