2015-11-18 06:14:39 +00:00
|
|
|
import Data.List (maximumBy)
|
|
|
|
|
import Data.Ord (comparing)
|
|
|
|
|
|
2018-06-22 20:57:24 +00:00
|
|
|
collatz :: Int -> Int
|
|
|
|
|
collatz n
|
|
|
|
|
| even n = n `div` 2
|
|
|
|
|
| otherwise = 3 * n + 1
|
|
|
|
|
|
2017-09-23 10:01:46 +02:00
|
|
|
hailstone :: Int -> [Int]
|
|
|
|
|
hailstone = takeWhile (/= 1) . iterate collatz
|
2015-11-18 06:14:39 +00:00
|
|
|
|
2017-09-23 10:01:46 +02:00
|
|
|
longestChain :: Int
|
|
|
|
|
longestChain =
|
2018-06-22 20:57:24 +00:00
|
|
|
fst $
|
|
|
|
|
maximumBy (comparing snd) $ (,) <*> (length . hailstone) <$> [1 .. 100000]
|
2015-11-18 06:14:39 +00:00
|
|
|
|
2017-09-23 10:01:46 +02:00
|
|
|
--TEST -------------------------------------------------------------------------
|
2018-06-22 20:57:24 +00:00
|
|
|
main :: IO ()
|
2017-09-23 10:01:46 +02:00
|
|
|
main =
|
|
|
|
|
mapM_
|
|
|
|
|
putStrLn
|
|
|
|
|
[ "Collatz sequence for 27: "
|
|
|
|
|
, (show . hailstone) 27
|
|
|
|
|
, "The number " ++ show longestChain
|
|
|
|
|
, "has the longest hailstone sequence for any number less then 100000. "
|
|
|
|
|
, "The sequence has length: " ++ (show . length . hailstone $ longestChain)
|
|
|
|
|
]
|