-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp41.go
87 lines (72 loc) · 1.32 KB
/
p41.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
81
82
83
84
85
86
87
package main
import (
"fmt"
"math"
"sort"
"time"
)
func IsPrime(prime []int, x int) bool {
bound := int(math.Sqrt(float64(x)))
if x%bound == 0 {
return false
}
for _, p := range prime {
if p >= bound {
return true
} else if x%p == 0 {
return false
}
}
return true
}
func Dtoi(digits []int, len int) int {
sum := 0
for i := 0; i < len; i++ {
sum = sum*10 + digits[i]
}
return sum
}
func main() {
start := time.Now()
prime, maxP := []int{2, 3, 5, 7, 11, 13}, 13
for maxP < int(math.Sqrt(float64(987654321))) {
maxP += 2
if IsPrime(prime, maxP) {
prime = append(prime, maxP)
}
}
digits := make([]int, 9)
done := false
for n := 9; !done && n > 3; n-- {
// init
for i := 0; i < n; i++ {
digits[i] = n - i
}
for {
curr := Dtoi(digits, n)
if curr%2 != 0 && IsPrime(prime, curr) {
fmt.Println(curr)
done = true
break
}
for i := n - 1; i > 0; i-- {
if digits[i] < digits[i-1] {
for j := n - 1; j > i-1; j-- {
if digits[j] < digits[i-1] {
digits[j], digits[i-1] = digits[i-1], digits[j]
break
}
}
// reorder
sort.Sort(sort.Reverse(sort.IntSlice(digits[i:n])))
break
}
}
if digits[0] == 1 && digits[n-1] == n {
break
}
}
}
elapsed := time.Since(start)
fmt.Println("Elasped:", elapsed)
}