import qualified Data.List as L
import Control.Monad

main = interact (show . solve . read)

p_list = reverse $ L.sort
    [ 6
    , 36
    , 216
    , 1296
    , 7776
    , 46656
    , 9
    , 81
    , 729
    , 6561
    , 59049]

hoge :: (Int, Int) -> Int -> [(Int, Int)]
hoge (c, n) s =
    let
        p =  n `div` s
    in
        if p < 9 then map (\t -> (c + t, n - s * t)) [0..p] else []

solve :: Int -> Int
solve n = foldl min 100000 $ map (\(a, b) -> a + b) $ foldl (\xs p -> join $ map (\n' -> hoge n' p) xs) [(0, n)] p_list

