module S = Set.Make (struct type t = int let compare = compare end) ;;

Scanf.scanf "%d" (fun n ->
    let add k acc =
        let rec loop i acc =
            if i > 100000 then acc else loop (i * k) (S.add i acc)
        in
        loop k acc
    in
    let l = add 9 (add 6 (S.singleton 1)) in
    let a = Array.make (n + 1) n in
    a.(0) <- 0;
    S.iter (fun i ->
        for j = i to n do
            if a.(j - i) + 1 < a.(j) then a.(j) <- a.(j - i) + 1
        done
    ) l;
    Printf.printf "%d\n" a.(n)
)