program c

integer :: n,i(6),j(5),sum,delta,max_itr=100000
integer :: jj(5) = (/ 9**1, 9**2, 9**3, 9**4, 9**5 /)
integer :: ii(6) = (/ 6**1, 6**2, 6**3, 6**4, 6**5, 6**6 /)
read(*,*) n

do i1=0,5
do i2=0,5
do i3=0,5
do i4=0,5
do i5=0,5
do i6=0,2
do j1=0,5
do j2=0,5
do j3=0,5
do j4=0,5
do j5=0,1
 
delta = n - (i1*6**1 + i2*6**2 + i3*6**3 + i4*6**4 + i5*6**5 + i6*6**6 + j1*9**1 + j2*9**2 + j3*9**3 + j4*9**4 + j5*9**5)

if(delta >= 0 .and. delta <= 6) then
max_itr = min(max_itr, delta+i1+i2+i3+i4+i5+i6+j1+j2+j3+j4+j5)
endif

enddo
enddo
enddo
enddo
enddo
enddo
enddo
enddo
enddo
enddo
enddo

write(*,*) max_itr

end program