#include using namespace std; typedef long long ll; #define REP(i,n) for(int i=0; i #define VLL vector #define VVI vector> #define VVLL vector> #define VC vector #define VS vector #define VVC vector> #define VB vector #define VVB vector> #define fore(i,a) for(auto &i:a) typedef pair P; template bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; } template bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; } const int INF = 1 << 29; const ll INFL = 1LL << 60; const ll mod = 1000000007; int main() { int q; cin >> q; REP(_, q) { ll a, b, c; cin >> a >> b >> c; if (c == 1) { cout << -1 << endl; } else { VI d; if (a < c) { cout << b << endl; } else if (a < c + c) { cout << b + b << endl; } else { while (a) { d.push_back(a%c); a /= c; } ll ans = b; REP(i, d.size() - 1) { if (d[i] == 0)ans += b; else ans += b + b; } if (d[d.size() - 1] == 1) { ans -= b; if (d[d.size() - 2] == 0)ans += b; } cout << ans << endl; } } } }