import Data.Char (digitToInt) import Data.List (nub) factors :: Integral a => a -> [a] factors n = [f | f <- [1 .. n], mod n f == 0] numToDigits :: (Integral a, Show a) => a -> [Int] numToDigits = fmap digitToInt . show gcdOfPermutation :: Integer -> Integer gcdOfPermutation n | length (nub ds) == 1 = n | otherwise = maximum $ filter (\f -> mod n f == 0) (factors $ fromIntegral $ foldr1 gcd xs) where ds = numToDigits n xs = [9 * abs (ds !! i - ds !! j) | let m = length ds, i <- [0 .. m - 1], j <- [0 .. i - 1]] main :: IO () main = do n <- readLn :: IO Integer print $ gcdOfPermutation n