-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package day210 | ||
|
||
// LongestCollatzSequence returns the number with the longest | ||
// sequence. | ||
// First result is the number, second number is the length of the sequence. | ||
func LongestCollatzSequence(max int) (int, int) { | ||
var n, longest int | ||
for i := max; i > 0; i-- { | ||
count := 0 | ||
v := i | ||
for v != 1 { | ||
if v%2 == 0 { | ||
v /= 2 | ||
} else { | ||
v = 3*v + 1 | ||
} | ||
count++ | ||
} | ||
if count > longest { | ||
longest = count | ||
n = i | ||
} | ||
} | ||
return n, longest | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package day210 | ||
|
||
import ( | ||
"testing" | ||
) | ||
|
||
func TestLongestCollatzSequence(t *testing.T) { | ||
t.Parallel() | ||
t.Skip("unskip test to verify result. takes too long to run") | ||
n, length := LongestCollatzSequence(1000000) | ||
if n != 837799 || length != 524 { | ||
t.Errorf("Expected (837799,524), got (%v,%v)", n, length) | ||
} | ||
} | ||
|
||
func TestLongestCollatzSequenceSmaller(t *testing.T) { | ||
t.Parallel() | ||
n, length := LongestCollatzSequence(10) | ||
if n != 9 || length != 19 { | ||
t.Errorf("Expected (9, 19), got (%v,%v)", n, length) | ||
} | ||
} | ||
|
||
func BenchmarkLongestCollatzSequence(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
LongestCollatzSequence(10) | ||
} | ||
} |