-
Notifications
You must be signed in to change notification settings - Fork 0
/
collatz5.go
71 lines (59 loc) · 991 Bytes
/
collatz5.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
package main
import (
"fmt"
"log"
"os"
"strconv"
)
type CollatzSequence map[int64]int64
func main() {
max, err := strconv.Atoi(os.Args[1])
if err != nil {
log.Fatal(err)
}
var seq CollatzSequence
seq = make(map[int64]int64)
seq.add(1, 0)
fmt.Println("digraph g {")
printNode(1)
for i := 2; i <= max; i++ {
i := int64(i)
if !seq.appears(i) {
collatz(i, seq)
fmt.Println()
}
}
fmt.Println("}")
}
func collatz(n int64, seq CollatzSequence) {
for n != 1 {
if seq.appears(n) {
break
}
printNode(n)
last := n
if (n & 0x01) == 0x01 {
n = 3*n + 1
} else {
n /= 2
}
if !seq.appears(n) {
printNode(n)
}
printEdge(last, n)
seq.add(last, n)
}
}
func (cs CollatzSequence) appears(n int64) bool {
_, ok := cs[n]
return ok
}
func (cs CollatzSequence) add(n, m int64) {
cs[n] = m
}
func printNode(n int64) {
fmt.Printf("N%d [label=\"%d\"];\n", n, n)
}
func printEdge(from, to int64) {
fmt.Printf("N%d -> N%d;\n", from, to)
}