Created
June 5, 2017 08:17
-
-
Save malisetti/078ecdf80115daf720a28b0063bb5462 to your computer and use it in GitHub Desktop.
Longest Collatz sequence under one million
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
package main | |
func main() { | |
onem := 1000000 | |
visited := map[int]int{} | |
maxstep := 1 | |
var maxn int | |
for i := 1; i <= onem; i++ { | |
n := i | |
if _, ok := visited[n]; !ok { | |
steps := 0 | |
for { | |
if n <= 1 { | |
break | |
} | |
if _, ok := visited[n]; !ok { | |
n = collatz(n) | |
steps++ | |
} else { | |
steps += visited[n] | |
break | |
} | |
} | |
if steps > maxstep { | |
maxstep = steps | |
maxn = i | |
} | |
visited[i] = steps | |
} | |
} | |
println(maxn, visited[maxn]+1) | |
} | |
func collatz(n int) int { | |
if n%2 == 0 { | |
return n / 2 | |
} | |
return n*3 + 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment