123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- # Sieve of Eratosthenes, in python
-
- from numpy import array, zeros, int8
- from time import process_time
-
-
- def sieve(to):
- """Construct a sieve of Eratosthenes up to the value of 'to'; return all
- primes below this number.
- """
- zarr = zeros(to, int8)
- zarr[0:2] = 1
- for i in range(2, to):
- if zarr[i] == 1:
- continue
- for x in range(i, ((to - 1) // i) + 1):
- zarr[i * x] = 1
- avals = array(range(to))
- return avals[zarr[range(to)] == 0]
-
-
- def sieval(to):
- """Run sieve algorithm up to 'to'; return process time, number of primes,
- and last prime calculated (in that order).
-
- 'to' must be greater than 2.
- """
- t1 = process_time()
- sh = sieve(to)
- te = process_time() - t1
- ls = len(sh)
- return te, ls, sh[ls - 1]
-
-
- def sievemsg(to):
- """Format sieval output for sieve up to 'to'
-
- 'to' must be greater than 2.
- """
- t, n, largest = sieval(to)
- rs = ("There are {1} prime numbers smaller than {3}; "
- "the largest is {2}. This "
- "calculation took {0:.2f} seconds via the sieve of "
- "Eratosthenes.".format(t, n, largest, to))
- return rs
|