#include namespace { #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic warning "-Wunused-function" using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; } int main() { ios::sync_with_stdio(false); cin.tie(0); int tt; cin >> tt; while(tt--) { ll x, y, a; cin >> x >> y >> a; auto digits = [](ll x, ll a) { VL d; while(x) d.emplace_back(x % a), x /= a; return d; }; VL dx = digits(x, a); VL dy = digits(y, a); int sz = max(dx.size(), dy.size()); dx.resize(sz); dy.resize(sz); VL vx(sz + 1), vy(sz + 1); rrep(i, sz) { vx[i] = a * vx[i + 1] + dx[i]; vy[i] = a * vy[i + 1] + dy[i]; } ll ans = 4e18; rep(to, sz + 1) { ll x0 = x; rep(_, to) x0 /= a; rep(at, sz + 1) { ll dp[2]{to + abs(vy[at] - x0), to + abs(vy[at] + 1 - x0)}; for(int i = at - 1; i >= 0; i--) { if (dp[0] >= ans && dp[1] >= ans) break; ll ndp[2]{(ll)4e18, (ll)4e18}; rep(x, 2) rep(y, 2) { ll p = (vy[i + 1] + x) * a; ll cost = 1 + abs(vy[i] + y - p); chmin(ndp[y], dp[x] + cost); } swap(dp, ndp); } chmin(ans, dp[0]); } } cout << ans << '\n'; } }