#include #include #include using namespace std; typedef long long ll; const ll INF = 2000000000000000000; struct S { ll prefix; ll prefix_dist; ll prefixpp_dist; }; void solve() { int t; cin >> t; while(t--) { ll x, y, a; vector dp; cin >> x >> y >> a; ll c = 0; dp.push_back(S{y, INF, INF}); while(true) { dp.back().prefix_dist = min(dp.back().prefix_dist, c + abs(y - x)); dp.back().prefixpp_dist = min(dp.back().prefixpp_dist, c + abs(y + 1 - x)); if(y == 0 && x == 0) { break; } if(y >= x) { y /= a; dp.push_back(S{y, INF, INF}); } else { x /= a; c++; } } int n = dp.size(); for(int i = n - 2; i >= 0; i--) { dp[i].prefix_dist = min({dp[i].prefix_dist, dp[i + 1].prefix_dist + dp[i].prefix - dp[i + 1].prefix * a + 1, dp[i + 1].prefixpp_dist + (dp[i + 1].prefix + 1) * a - dp[i].prefix + 1}); dp[i].prefixpp_dist = min({dp[i].prefixpp_dist, dp[i + 1].prefix_dist + (dp[i].prefix + 1) - dp[i + 1].prefix * a + 1, dp[i + 1].prefixpp_dist + (dp[i + 1].prefix + 1) * a - (dp[i].prefix + 1) + 1}); } cout << dp[0].prefix_dist << endl; } } int main() { solve(); }