mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 21:24:46 +01:00
rename directory
This commit is contained in:
79
14_longest_collatz_sequence/collatz_test.go
Normal file
79
14_longest_collatz_sequence/collatz_test.go
Normal file
@@ -0,0 +1,79 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCollatzNext(t *testing.T) {
|
||||
tt := []struct {
|
||||
name string
|
||||
input int
|
||||
want int
|
||||
}{
|
||||
{
|
||||
"1",
|
||||
1,
|
||||
1,
|
||||
},
|
||||
{
|
||||
"2",
|
||||
2,
|
||||
1,
|
||||
},
|
||||
{
|
||||
"3",
|
||||
3,
|
||||
10,
|
||||
},
|
||||
{
|
||||
"13",
|
||||
13,
|
||||
40,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := CollatzNext(tc.input)
|
||||
if got != tc.want {
|
||||
t.Errorf("CollatzNext(%d)=%d, want %d", tc.input, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEven(t *testing.T) {
|
||||
tt := []struct {
|
||||
name string
|
||||
input int
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
"1",
|
||||
1,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"2",
|
||||
2,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"99",
|
||||
99,
|
||||
false,
|
||||
},
|
||||
{
|
||||
"100",
|
||||
100,
|
||||
true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := IsEven(tc.input)
|
||||
if got != tc.want {
|
||||
t.Errorf("IsEven(%d)=%v, want %v", tc.input, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
41
14_longest_collatz_sequence/main.go
Normal file
41
14_longest_collatz_sequence/main.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
num := 0
|
||||
ml := 0
|
||||
for i := 1000000; i > 1; i-- {
|
||||
n := i
|
||||
count := 1
|
||||
for {
|
||||
n = CollatzNext(n)
|
||||
if n == 1 {
|
||||
break
|
||||
}
|
||||
count++
|
||||
}
|
||||
if count > ml {
|
||||
ml = count
|
||||
num = i
|
||||
}
|
||||
}
|
||||
fmt.Println("largest collatz is", num, "len:", ml)
|
||||
}
|
||||
|
||||
func CollatzNext(n int) int {
|
||||
if n == 1 {
|
||||
return 1
|
||||
} else if IsEven(n) {
|
||||
return n / 2
|
||||
} else {
|
||||
return 3*n + 1
|
||||
}
|
||||
}
|
||||
|
||||
func IsEven(n int) bool {
|
||||
if n > 1 && n%2 == 0 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user