#include <iostream>
using namespace std;
int A(int n) {
if (n == 1)
return 0;
// k == 3^m
int k = 1;
while (3*k < n) k *= 3;
return A((n - 1) % k + 1) + ((n <= 2*k) ? k : 2*k);
}
int
main()
{
for (auto n: {1, 2, 3, 4, 5, 6, 9, 123457, 1000000000})
cout << n << " " << A(n) << endl;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBBKGludCBuKSB7CiAgICBpZiAobiA9PSAxKQogICAgICAgIHJldHVybiAwOwogICAgCiAgICAvLyBrID09IDNebQogICAgaW50IGsgPSAxOwogICAgd2hpbGUgKDMqayA8IG4pIGsgKj0gMzsKCiAgICByZXR1cm4gQSgobiAtIDEpICUgayArIDEpICsgKChuIDw9IDIqaykgPyBrIDogMiprKTsKfQoKaW50Cm1haW4oKQp7CiAgICBmb3IgKGF1dG8gbjogezEsIDIsIDMsIDQsIDUsIDYsIDksIDEyMzQ1NywgMTAwMDAwMDAwMH0pCiAgICAgICAgY291dCA8PCBuIDw8ICIgIiA8PCBBKG4pIDw8IGVuZGw7Cn0K