1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import Data.List
digits b = reverse . map (`mod` b) . takeWhile (> 0) . iterate (`div` b)
undigits b = foldl' (\a b -> b * a + b) 0
step b = sum . map (^2) . digits b
untilCycle f x = reverse $ go x []
where go x xs
| x `elem` xs = x : xs
| otherwise = go (f x) (x:xs)
getCycle f x = dropWhile (/= last xs) xs
where xs = untilCycle f x
showChain b = untilCycle (step b)
reaches b = minimum . getCycle (step b)
allReached b = nub $ map (reaches b) [1 .. b^4]
|