#include using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() #define fi first #define se second template inline bool chmax(A &a, B b) { if (a inline bool chmin(A &a, B b) { if (a>b) { a=b; return 1; } return 0; } using ll = long long; using pii = pair; constexpr ll INF = 1ll<<30; constexpr ll longINF = 1ll<<60; constexpr ll MOD = 1000000007; constexpr bool debug = 0; //---------------------------------// ll solve(ll A, ll B, ll C) { if (C == 1) return -1; ll cnt = 0; bool f = false; while (A > 0) { if (A > C && A <= C*C && A <= 2*(C-1)) { f = true; } if (A % C > 0) { A -= A % C; cnt++; } if (A > 0) { A /= C; cnt++; } } if (f) cnt--; ll res = cnt * B; return res; } int main() { int Q; cin >> Q; while (Q--) { int A, B, C; scanf("%d %d %d", &A, &B, &C); cout << solve(A, B, C) << endl; } return 0; }