-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackwards_read_primes.go
73 lines (59 loc) · 1.01 KB
/
backwards_read_primes.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
package backwards_read_primes
import (
"math"
"sort"
"strconv"
"sync"
)
func BackwardsPrime(start int, stop int) []int {
var out []int
ch := make(chan int)
wg := new(sync.WaitGroup)
for i := start; i <= stop; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
if !IsPrime(i) {
return
}
m := mirror(i)
if m == i {
return
}
if !IsPrime(m) {
return
}
ch <- i
}(i)
}
go func() {
wg.Wait()
close(ch)
}()
for i := range ch {
out = append(out, i)
}
sort.Ints(out)
return out
}
func IsPrime(n int) bool {
// See algorithm here https://whatis.techtarget.com/definition/prime-number.
// Should have used https://golang.org/src/math/big/prime.go instead.
for m := math.Ceil(math.Sqrt(float64(n))); m > 1; m-- {
if math.Mod(float64(n), m) == 0 {
return false
}
}
return true
}
func mirror(n int) int {
var m string
for _, r := range strconv.Itoa(n) {
m = string(r) + m
}
out, err := strconv.Atoi(m)
if err != nil {
panic(err)
}
return out
}