|
@@ -1,46 +1,13 @@
|
1
|
1
|
import random
|
|
2
|
+import psimp as p
|
2
|
3
|
|
3
|
|
-pto100 = [
|
4
|
|
- 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
|
5
|
|
- 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
|
6
|
|
-]
|
7
|
|
-
|
8
|
|
-
|
9
|
|
-def in_100(x):
|
10
|
|
- """Check if x is in the primes less than 100 i.e., in the first 25 primes.
|
11
|
|
- Useful for e.g. the first step in Baillie–PSW.
|
12
|
|
- """
|
13
|
|
- return x in pto100
|
14
|
|
-
|
15
|
|
-
|
16
|
|
-def hund_div(x):
|
17
|
|
- """Check if x is divisible by any of the 25 primes less than 100. Returns 0
|
18
|
|
- if there is no such divisor, otherwise returns the first divisor.
|
19
|
|
- """
|
20
|
|
- for v in pto100:
|
21
|
|
- if v >= x:
|
22
|
|
- return 0
|
23
|
|
- if x % v == 0:
|
24
|
|
- return v
|
25
|
|
- return 0
|
26
|
|
-
|
27
|
|
-
|
28
|
|
-def trd(x):
|
29
|
|
- """Express x as 2^r * d. Returns two values, r and d.
|
30
|
|
- """
|
31
|
|
- count = 0
|
32
|
|
- xc = x
|
33
|
|
- while xc % 2 == 0:
|
34
|
|
- count = count + 1
|
35
|
|
- xc = xc // 2
|
36
|
|
- return count, xc
|
37
|
4
|
|
38
|
5
|
|
39
|
6
|
def MillerRabinRandom(n, k):
|
40
|
7
|
"""Carry out a Miller-Rabin test on n with k iterations, choosing random
|
41
|
8
|
values for a.
|
42
|
9
|
"""
|
43
|
|
- r, d = trd(n-1)
|
|
10
|
+ r, d = p.trd(n-1)
|
44
|
11
|
for iter in range(k):
|
45
|
12
|
a = random.randint(2, n - 2)
|
46
|
13
|
x = pow(a, d, n)
|
|
@@ -60,7 +27,7 @@ def MillerRabinRandom(n, k):
|
60
|
27
|
def MillerRabin(n, base):
|
61
|
28
|
"""Carry out a Miller-Rabin test on n with a specified base.
|
62
|
29
|
"""
|
63
|
|
- r, d = trd(n-1)
|
|
30
|
+ r, d = p.trd(n-1)
|
64
|
31
|
a = base
|
65
|
32
|
x = pow(a, d, n)
|
66
|
33
|
if x == 1 or x == n - 1:
|
|
@@ -78,8 +45,8 @@ for base in range(2, 16):
|
78
|
45
|
for i in range(2, 10000):
|
79
|
46
|
if i % 2 == 0 or base % i == 0:
|
80
|
47
|
continue
|
81
|
|
- if MillerRabin(i, base) == (hund_div(i) == 0):
|
82
|
|
- print(i, hund_div(i), MillerRabin(i, base))
|
|
48
|
+ if MillerRabin(i, base) == (p.hund_div(i) == 0):
|
|
49
|
+ print(i, p.hund_div(i), MillerRabin(i, base))
|
83
|
50
|
print()
|
84
|
51
|
|
85
|
52
|
MillerRabin(28, 3)
|