#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(); ll ans = max(sz - 2, 0); for (int i = 1; i < sz; i += 2) { ll val = v[i - 1] * c + v[i]; if (val == 0) continue; ans += (val <= 2 * (c - 1) ? 2 : 3); } 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; }