open Scanf
open Printf

let fold_left1 f lst = List.fold_left f (List.hd lst) (List.tl lst)
let rec seq k n = if k = n then [n] else k :: seq (k+1) n

let rec g k n = if n < k then n else n mod k + g k (n / k)
let f n = fold_left1 min @@ List.map (fun i -> g 6 i + g 9 (n-i)) (seq 0 n)

let () = let ans = scanf "%d\n" f in
  printf "%d\n" ans