split :: String -> [String] split = go ("", []) where go :: (String, [String]) -> String -> [String] go (a, acc) "" = acc <> [a] go (a, acc) (' ' : xs) = go ("", acc <> [a]) xs go (a, acc) (x : xs) = go (a <> [x], acc) xs prompt :: IO [String] prompt = do split <$> getLine bin :: Int -> [Int] bin x | x <= 1 = [x] | otherwise = let (n, r) = x `quotRem` 2 in bin n <> [r] d :: Int -> Int d = sum . bin solve :: Int -> Int solve n = go 1 1 [] where go :: Int -> Int -> [Int] -> Int go c p m | n == p = c | p `elem` m = -1 | otherwise = let proceed = p + d p in go (c + 1) (if proceed > n then p - d p else proceed) (p : m) main :: IO () main = do n :: Int <- read . head <$> prompt print $ solve n