main=readLn>>=print.(\n->(if n<6 then n else ((mod n 3)+(f (quot n 3)))))
 where f n = if (even n) then (g (quot n 2) 0) else (g ((quot n 2)-1) 1)
       g a b = if a<3 then (h a b) else (min (h a b) (g (a-3) (b+2)))
       h a b = (i a)+(j b)
       i a = sum[mod(quot a (6^x))6|x<-[0..5]]
       j b = sum[mod(quot b (9^x))9|x<-[0..4]]