|
@@ -0,0 +1,42 @@
|
|
1
|
+# Sieve of Eratosthenes, in python
|
|
2
|
+
|
|
3
|
+from numpy import array, zeros, int8
|
|
4
|
+from time import process_time
|
|
5
|
+
|
|
6
|
+def sieve(to):
|
|
7
|
+ """Construct a sieve of Eratosthenes up to the value of 'to'; return all
|
|
8
|
+ primes below this number.
|
|
9
|
+ """
|
|
10
|
+ zarr = zeros(to, int8)
|
|
11
|
+ zarr[0:2] = 1
|
|
12
|
+ for i in range(2, to):
|
|
13
|
+ if zarr[i] == 1:
|
|
14
|
+ continue
|
|
15
|
+ for x in range(i, ((to - 1) // i) + 1):
|
|
16
|
+ zarr[i * x] = 1
|
|
17
|
+ avals = array(range(to))
|
|
18
|
+ return avals[zarr[range(to)] == 0]
|
|
19
|
+
|
|
20
|
+def sieval(to):
|
|
21
|
+ """Run sieve algorithm up to 'to'; return process time, number of primes,
|
|
22
|
+ and last prime calculated (in that order).
|
|
23
|
+
|
|
24
|
+ 'to' must be greater than 2.
|
|
25
|
+ """
|
|
26
|
+ t1 = process_time()
|
|
27
|
+ sh = sieve(to)
|
|
28
|
+ te = process_time() - t1
|
|
29
|
+ ls = len(sh)
|
|
30
|
+ return te, ls, sh[ls - 1]
|
|
31
|
+
|
|
32
|
+def sievemsg(to):
|
|
33
|
+ """Format sieval output for sieve up to 'to'
|
|
34
|
+
|
|
35
|
+ 'to' must be greater than 2.
|
|
36
|
+ """
|
|
37
|
+ t, n, l = sieval(to)
|
|
38
|
+ rs = ("There are {1} prime numbers smaller than {3}; the largest is {2}. This "
|
|
39
|
+ "calculation took {0:.2f} seconds via the sieve of "
|
|
40
|
+ "Eratosthenes.".format(t, n, l, to))
|
|
41
|
+ return rs
|
|
42
|
+
|