-
Notifications
You must be signed in to change notification settings - Fork 0
/
collatz.go
108 lines (95 loc) · 2.17 KB
/
collatz.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"html/template"
"log"
"math/big"
"net/http"
"os"
)
var big_zero = big.NewInt(0)
var big_one = big.NewInt(1)
var big_three = big.NewInt(3)
func collatz_step(a *big.Int) {
if a.Bit(0) == 0 {
a.Rsh(a, 1)
} else {
a.Mul(a, big_three)
a.Add(a, big_one)
}
}
func collatz_step_count_maximum(next_step, max, counter *big.Int) {
n := big.NewInt(0)
n.Set(next_step)
collatz_step(next_step)
max.Set(n)
for n.Cmp(big_one) > 0 {
collatz_step(n)
if n.Cmp(max) > 0 {
max.Set(n)
}
counter.Add(counter, big_one)
}
}
var tmpl *template.Template
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func main() {
var err error
tmpl_bytes, _ := templatesIndexTmplBytes()
tmpl, err = template.New("index.tmpl").Parse(string(tmpl_bytes))
if err != nil {
log.Fatal(err)
}
http.Handle("/static/", http.FileServer(AssetFile()))
http.HandleFunc("/", page_handler)
log.Fatal(http.ListenAndServe(getEnv("BIND_ADDR", "0.0.0.0:8000"), nil))
}
type PageData struct {
Current *big.Int
Steps *big.Int
Maximum *big.Int
NextStep *big.Int
ReachDown *big.Int
ReachUp *big.Int
AtOne bool
}
func page_handler(w http.ResponseWriter, r *http.Request) {
var number *big.Int
if r.URL.Path == "/" {
number = big.NewInt(1)
} else {
number = big.NewInt(0)
_, success := number.SetString(r.URL.Path[1:], 10)
if !success || number.Cmp(big_zero) <= 0 {
w.WriteHeader(404)
w.Write([]byte("404 page not found"))
return
}
}
data := PageData{
Current: number,
Steps: big.NewInt(0),
Maximum: big.NewInt(0),
NextStep: big.NewInt(0).Set(number),
ReachDown: nil,
ReachUp: nil,
AtOne: number.Cmp(big_one) == 0,
}
collatz_step_count_maximum(data.NextStep, data.Maximum, data.Steps)
temp_div := big.NewInt(0)
temp_mod := big.NewInt(0)
temp_div.Sub(number, big_one)
temp_div.DivMod(temp_div, big_three, temp_mod)
if temp_mod.Cmp(big_zero) == 0 && temp_div.Cmp(big_one) > 0 {
data.ReachDown = temp_div
}
data.ReachUp = big.NewInt(0).Lsh(number, 1)
err := tmpl.ExecuteTemplate(w, "index.tmpl", data)
if err != nil {
log.Println(err)
}
}