#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll=long long; template using V = vector; template using P = pair; using vll = V; using vvll = V; #define rep(i, k, n) for (ll i=k; i<(ll)n; ++i) #define REP(i, n) rep(i, 0, n) #define ALL(v) v.begin(),v.end() template inline bool chmax(T& a, T b) {if (a inline bool chmin(T& a, T b) {if (a>b) {a=b; return true;} return false;} const ll MOD = 1000000007; const ll HIGHINF = (ll)1e18; int main() { cin.tie(0); ios::sync_with_stdio(false); ll q; cin >> q; while (q-->0) { ll a, b, c; cin >> a >> b >> c; if (c==1) cout << "-1\n"; else { ll tmpa = a; vll bit; while (tmpa>0) { bit.push_back(tmpa%c); tmpa /= c; } reverse(ALL(bit)); ll m = bit.size(); vll sum(m+1, 0), powC(m, 1), dp(m+1, a); rep(i, 1, m) powC[i] = powC[i-1]*c; rep(i, 1, m+1) REP(j, i) sum[i] += bit[j]*powC[i-j-1]; dp[0] = 0; REP(i, m) { if (sum[i]*c == sum[i+1]) chmin(dp[i+1], dp[i]+1); if (sum[i]+c-1 >= sum[i+1]) chmin(dp[i+1], dp[i]+1); if (sum[i]*c+c-1 >= sum[i+1]) chmin(dp[i+1], dp[i]+2); if (i+2<=m && sum[i]+2*c-2 >= sum[i+2]) chmin(dp[i+2], dp[i]+2); } cout << dp[m]*b << '\n'; } } return 0; }