#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,long long> mp; long long get(long long x,long long y,long long z){ if(y<=x)return abs(y-x); if(y<=1)return abs(y-x); if(mp.count({x,y,z}))return mp[{x,y,z}]; long long ret = abs(x-y); long long r = y%z; if(r==0){ ret = min(ret,get(x,y/z,z)+1); } else{ ret = min(ret,get(x,y/z,z)+1+r); ret = min(ret,get(x,y/z+1,z)+1+(z-r)); } mp[{x,y,z}] = ret; return ret; } int main(){ int _t; cin>>_t; rep(_,_t){ mp.clear(); long long x,y,z; cin>>x>>y>>z; long long ans = Inf64; rep(i,61){ ans = min(ans,get(x,y,z)+i); if(x==0)break; x /= z; } cout<