let rec digits r = function
  | 0 -> []
  | n -> n mod r :: digits r (n / r)
 
let () = Scanf.scanf "%d" @@ fun n ->
  Array.init (n + 1) (fun i ->
    List.fold_left ( + ) 0 (digits 6 i) + List.fold_left ( + ) 0 (digits 9 (n - i)))
  |> Array.fold_left min max_int
  |> Printf.printf "%d\n"