#include #define rep(i, n) for(int i = 0; i < (int)n; i++) using namespace std; using ll = long long; using P = pair; int main() { int q; cin >> q; rep(query, q) { ll a, b, c; cin >> a >> b >> c; if(c == 1) { cout << -1 << endl; continue; } vector d; while(a > 0) { d.push_back(a % c); a /= c; } ll ans = 1000; for(int i = (int)d.size() - 1; i >= 0; i--) { ll sum = i, tmp = 0; for(int j = (int)d.size() - 1; j >= i; j--) { tmp *= c; tmp += d[j]; } for(int j = i - 1; j >= 0; j--) { if(d[j]) sum++; } sum += tmp / (c - 1); if(tmp % (c - 1)) sum++; ans = min(ans, sum); } cout << ans * b << endl; } return 0; }