Problem:
Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16

Solution in Python (3.4.3) (judge verdict: Wrong Answer)

# ABC 099 解4 
import math
def getInt(): return int(input())
def zeros(n): return [0]*n
def db(x): 
    global debug
    if debug: print(x)
def atmUnit(base, req):
    if req<=0: return 0
    else: 
        unit = base ** int(math.log10(req)/math.log10(base))
        return unit # 引き出せる最大の単位量
def atm9(req): return atmUnit(9, req)
def atm6(req): return atmUnit(6, req)
def atm(req):
    db(('req',req))
    if req<=0: return 0
    u9 = atm9(req)
    c9 = req // u9
    db (('unit9,count9',u9,c9))
    u6 = atm6(req)
    c6 = req // u6
    db (('unit6,count6',u6,c6))
    c6 = c6 + atm(req-c6*u6)
    remainMax = min(u9,u6)
    #db(('remainMax:',remainMax))
    minCount = 999999
    for i in range(c9+1):
        for j in range(c6+1):
            if req-i*u9-j*u6>=remainMax: continue
            if req-i*u9-j*u6<0: continue
            minCount = min(minCount, i+j+atm(req-i*u9-j*u6))
    #db(minCount)
    return minCount
    
debug = False
N = getInt()
print(atm(N))