#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read(){ll x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;}
inline void write(ll x){if (x < 0) x = ~x + 1, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}
#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b,ll mod){ll res = 1;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;}
const int maxn=1e6+7;
vector<ll>v1,v2;
map<ll,int>dp;
void init(){
ll x=6;
while(x<=1e12) v1.push_back(x),x*=6;
x=9;
while(x<=1e12) v2.push_back(x),x*=9;
}
int dfs(ll n){
if(!n||dp[n]) return dp[n];
dp[n]=0x3f3f3f3f;
int pos=upper_bound(v1.begin(), v1.end(),n)-v1.begin()-1;
if(pos>=0) dp[n]=min(dp[n],dfs(n-v1[pos])+1);
pos=upper_bound(v2.begin(),v2.end(),n)-v2.begin()-1;
if(pos>=0) dp[n]=min(dp[n],dfs(n-v2[pos])+1);
if(n<=5) dp[n]=min(dp[n],dfs(n-1)+1);
return dp[n];
}
int main(){
init();
int _=read;
while(_--){
ll n=read;
cout<<dfs(n)<<endl;
}
return 0;
}