0014.hs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. {-
  2. The following iterative sequence is defined for the set of positive integers:
  3. n -> n/2 (n is even)
  4. n -> 3n + 1 (n is odd)
  5. Using the rule above and starting with 13, we generate the following sequence:
  6. 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1.
  7. It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
  8. Which starting number, under one million, produces the longest chain?
  9. NOTE: Once the chain starts the terms are allowed to go above one million.
  10. -}
  11. import Data.List
  12. import Data.Maybe
  13. import Data.Function
  14. (|>) = (&)
  15. next_term :: Int -> Int
  16. next_term 1 = 1
  17. next_term x
  18. | even x = div x 2
  19. | otherwise = (x * 3) + 1
  20. gen_chain :: Int -> [Int]
  21. gen_chain 1 = [1]
  22. gen_chain s = [s] ++ gen_chain (next_term s)
  23. solution :: Int
  24. solution = chains !! (elemIndex biggest chains_size |> fromJust) |> head
  25. where
  26. chains = [1..1000000] |> map gen_chain
  27. -- For some reason if chains is used here it will fill all the memory
  28. chains_size = [1..1000000] |> map gen_chain |> map length
  29. biggest :: Int
  30. biggest = maximum chains_size
  31. main :: IO ()
  32. main = putStrLn ("Solution: " ++ show solution)