Problem:
Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36

Solution in Haskell (GHC 7.10.3) (judge verdict: Accepted)

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
import           Control.Monad.ST            (runST)
import qualified Data.Sequence               as S
import qualified Data.Vector.Unboxed.Mutable as VM

main :: IO ()
main = do
  k <- readLn
  print $ solve k

solve :: Int -> Int
solve k = runST $ do
  vs <- VM.replicate k False
  whileLeft (S.singleton (1, 1)) $ \q -> do
    let (n, d) S.:< q' = S.viewl q
    v <- VM.read vs n
    if | n == 0    -> return $ Right d
       | v         -> return $ Left q'
       | otherwise -> do
           VM.write vs n True
           return $ Left $ (((n * 10) `mod` k, d) S.<| q') S.|> ((n + 1) `mod` k, d + 1)

whileLeft :: Monad m => a -> (a -> m (Either a b)) -> m b
whileLeft x f = f x >>= \case
  Left l  -> whileLeft l f
  Right r -> return r