-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathis_probabalistic_prime.go
80 lines (72 loc) · 1.2 KB
/
is_probabalistic_prime.go
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"crypto/rand"
"fmt"
"math/big"
)
func IsProbabilisticPrime(n uint64, k uint64) (bool, error) {
// Miller-Rabin primality test
if n < 0 {
return false, fmt.Errorf("IsProbabilisticPrime: n must be non-negative")
}
if n <= 3 {
return true, nil
}
if n == 4 {
return false, nil
}
d := n - 1
//fmt.Printf("d: %d\n", d)
for d%2 != 0 {
d /= 2
}
for i := uint64(0); i < k; i++ {
if !MillerTest(n, d) {
return false, nil
}
}
return true, nil
}
func MillerTest(n, d uint64) bool {
a, _ := rand.Int(rand.Reader, new(big.Int).SetUint64(n-4))
a.Add(a, big.NewInt(2))
x := ModPow(a.Uint64(), d, n)
if x == 1 || x == n-1 {
return true
}
for j := d; j < n-1; j *= 2 {
x = ModPow(x, 2, n)
if x == 1 {
return false
}
if x == n-1 {
return true
}
}
return false
}
func ModPow(a, b, m uint64) uint64 {
result := new(big.Int).Exp(
new(big.Int).SetUint64(a),
new(big.Int).SetUint64(b),
new(big.Int).SetUint64(m),
)
return result.Uint64()
}
func IsPrime(n uint64) bool {
if n < 0 {
return false
}
if n <= 3 {
return true
}
if n%2 == 0 {
return false
}
for i := uint64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}