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 JavaScript (node.js v5.12) (judge verdict: Wrong Answer)

"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function main(input) {
  var lines = input.split('\n');

  var _splitNum = splitNum(lines[0]),
      _splitNum2 = _slicedToArray(_splitNum, 1),
      N = _splitNum2[0];

  var nums = [[1, 1]];

  for (var i = 6; i <= 100000; i *= 6) {
    nums.push([i, 1], [i * 2, 2]);
  }

  for (var _i2 = 9; _i2 <= 100000; _i2 *= 9) {
    nums.push([_i2, 1]);
  }

  nums.sort(function (_ref, _ref2) {
    var _ref3 = _slicedToArray(_ref, 2),
        a = _ref3[0],
        _ = _ref3[1];

    var _ref4 = _slicedToArray(_ref2, 2),
        b = _ref4[0],
        _2 = _ref4[1];

    return b - a;
  });
  var result = 0;
  var current = N;

  for (var _i3 = 0; _i3 < nums.length; _i3++) {
    var _nums$_i = _slicedToArray(nums[_i3], 2),
        num = _nums$_i[0],
        cost = _nums$_i[1];

    while (current >= num) {
      result += cost;
      current -= num;
    }
  }

  console.log(result);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));

function splitNum(line) {
  return line.split(/\s+/).map(function (n) {
    return parseInt(n);
  });
}