-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollatz.go
98 lines (92 loc) · 1.72 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
package main
import (
"fmt"
"os"
"strconv"
//"time"
)
func linear_collatz(init_num int) {
num := 0
count := 0
highest_number := 0
highest_count := 0
for i := 2; i < init_num; i++{
num = i
count = 0
for {
if num == 1 {
break
}
num1 := 0
if num%2 == 0 {
num1 = num/2
} else {
num1 = ((3*num)+1)
}
num = num1
count = count + 1
}
if count > highest_count {
highest_count = count
highest_number = i
}
}
fmt.Println(highest_count)
fmt.Println(highest_number)
}
func cached_linear_collatz(init_num int) {
m := make(map[int]int)
num := 0
count := 0
highest_number := 0
highest_count := 0
for i := 2; i < init_num; i++{
num = i
count = 0
for {
if num == 1 {
m[i] = count
break
}
num1 := 0
if m[num] != 0 {
count = count + m[num]
m[i] = count
break
} else {
if num%2 == 0 {
num1 = num/2
} else {
num1 = ((3*num)+1)
}
}
num = num1
count = count + 1
}
if count > highest_count {
highest_count = count
highest_number = i
}
}
fmt.Println(highest_count)
fmt.Println(highest_number)
}
func main() {
init_num := 1
method := ""
if len(os.Args) == 3 {
var arg_num, _ = strconv.Atoi(os.Args[1])
init_num = arg_num
method = os.Args[2]
} else if len(os.Args) == 2 {
var arg_num, _ = strconv.Atoi(os.Args[1])
init_num = arg_num
} else {
fmt.Println("Invalid amount of arguments")
}
if method == "" || method == "linear" {
linear_collatz(init_num)
} else if method == "cached" {
cached_linear_collatz(init_num)
}
}