#include #include #include using namespace std; using namespace atcoder; using mint = modint998244353; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf32 1000000001 #define Inf64 4000000000000000001 map mp; long long x,z; long long ans = Inf64; long long get(long long y){ if(y<=x)return abs(y-x); if(y<=1)return abs(y-x); if(mp.count(y))return mp[y]; long long ret = abs(x-y); if(ret>=ans)return ret; long long r = y%z; if(r==0){ ret = min(ret,get(y/z)+1); } else{ ret = min(ret,get(y/z)+1+r); ret = min(ret,get(y/z+1)+1+(z-r)); } mp[y] = ret; return ret; } int main(){ int _t; cin>>_t; rep(_,_t){ long long y; cin>>x>>y>>z; long long ans = Inf64; rep(i,61){ mp.clear(); ans = min(ans,get(y)+i); if(x==0)break; x /= z; } cout<