Skip to content

Instantly share code, notes, and snippets.

@smigniot
Created April 25, 2022 19:07
Show Gist options
  • Select an option

  • Save smigniot/e63b08320a610bc63628bc2a4512aaa5 to your computer and use it in GitHub Desktop.

Select an option

Save smigniot/e63b08320a610bc63628bc2a4512aaa5 to your computer and use it in GitHub Desktop.
A solution to some homework assignment
next n
| rem n 2 == 0 = div n 2
| otherwise = 3*n+1
collatz 1 = [1]
collatz n = n : (collatz (next n))
collatzLength n =
(n, length (collatz n))
bestOf (a, lengtha) (b, lengthb)
| lengthb > lengtha = (b, lengthb)
| otherwise = (a, lengtha)
longestSequence n =
foldl bestOf (1,1) (
map collatzLength [1..n])
solution n = let
(k,l) = longestSequence n
in ("Longest sequence for less than "
++(show n)++" has length "
++(show l)++" for starting k="
++(show k)++"\n")
main = interact f
where f input = solution (read input)
@smigniot
Copy link
Author

ghc collatz.hs && echo 10000 | ./collatz
Longest sequence for less than 10000 has length 262 for starting k=6171

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment