fork download
  1. import qualified Data.Array
  2. import Data.Word
  3. import Data.List
  4. import Data.Array.ST
  5. import Data.Array.MArray
  6. import Control.Monad.ST
  7. import Control.Monad
  8. import Data.Array.IArray
  9.  
  10. upperbound = 1000000
  11.  
  12. collatz_array_mutable =
  13. runSTUArray ( do
  14. arr <- newArray (1, upperbound) maxBound :: ST s (STUArray s Word64 Word16)
  15. writeArray arr 1 0
  16. forM_ [1..upperbound] (\i ->
  17. do
  18. {
  19. let
  20. next_i i = f ((if (even i) then i else 3 * i + 1) `div` 2)
  21. f i =
  22. do
  23. if i > upperbound
  24. then
  25. do
  26. new_elem <- next_i i
  27. return (new_elem + 1)
  28. else
  29. do
  30. elem <- readArray arr i
  31. if elem == maxBound
  32. then
  33. do
  34. new_elem <- next_i i
  35. writeArray arr i (new_elem + 1)
  36. return (new_elem + 1)
  37. else
  38. in
  39. f i
  40. }
  41. )
  42. return arr
  43. )
  44.  
  45. main =
  46. foldl1' (\(x1,x2) (y1,y2) -> if (x2 >= y2) then (x1, x2) else (y1, y2)) $! (assocs collatz_array_mutable)
  47.  
Success #stdin #stdout 0.74s 5680KB
stdin
Standard input is empty
stdout
(837799,329)