language: Python (python 2.7.3)
date: 1120 days 10 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'''Last modified on 24/05/2010
 
Author: Xavier Ho <contact@xavierho.com>
 
Dependencies: numpy'''
from math import sqrt
import numpy
 
###############################################################
# Prime numbers generator
def primes(limit=1000000):
    '''Returns a list of prime numbers less than the limit.'''
    return __numpy_primes(limit)
 
def xprimes(limit=1000000):
    '''Returns a generator of prime numbers less than the limit.'''
    return __numpy_xprimes(limit)
 
 
def __numpy_primes(limit=1000000):
    '''Returns a list of prime numbers up to the limit, using numpy and Sieve of Eratosthenes.'''
    primes = numpy.ones(limit, dtype=numpy.bool)
    for n in xrange(2, int(sqrt(limit))):
        if primes[n]:
            primes[n*n::n] = 0
    return numpy.nonzero(primes)[0][2:]
 
def __numpy_xprimes(limit=1000000):
    '''Returns a list of prime numbers up to the limit, using numpy and Sieve of Eratosthenes.'''
    primes = numpy.ones(limit, dtype=numpy.bool)
    for n in xrange(2, int(sqrt(limit))):
        if primes[n]:
            primes[n*n::n] = 0
    primes[:2] = 0
    return (x for x, p in enumerate(primes) if p)
 
###############################################################
 
if __name__ == '__main__':
    from time import time
    start = time()
#    p = primes()
    for p in xprimes(): pass
    print time() - start, "seconds" 
    print p