#include using namespace std; using ll = long long; ll solve(ll a, ll b, ll c) { if (c == 1) return -1; vector v; ll aa = a; while (aa > 0) { v.push_back(aa % c); aa /= c; } reverse(v.begin(), v.end()); int sz = v.size(); if (sz == 1) return b; ll ans = 0; if (v[1] == 0) ans += 2; else if (v[0] * c + v[1] <= 2 * (c - 1)) ans += 2; else ans += 3; ans += max(sz - 2, 0); for (int i = 2; i < sz; i++) { ans += (v[i] > 0); } ans *= b; return ans; } int main() { cin.tie(0); ios::sync_with_stdio(false); int q; cin >> q; for (int i = 0; i < q; i++) { ll a, b, c; cin >> a >> b >> c; cout << solve(a, b, c) << "\n"; } return 0; }