#include using namespace std; int main() { int Q; cin >> Q; assert(1<=Q&&Q<=20); while(Q--){ long long A,B,C; cin >> A >> B >> C; assert(1<=A&&A<=1000000000LL); assert(1<=B&&B<=1000000000LL); assert(1<=C&&C<=1000000000LL); if(C==1){ cout << -1 << endl; continue; } if(A v; while(A>0){ v.push_back(A%C); A /= C; } reverse(v.begin(),v.end()); long long ans = 0; long long cnt = v[0]*C+v[1]; if(v[1]==0 || 2*C-2>=cnt) ans += 2; else ans += 3; ans += (long long)v.size() - 2; for(int i = 2; i < v.size(); ++i) if(v[i]) ans += 1; ans *= B; assert(1<=ans&&ans<=1000000000000000000LL); cout << ans << endl; } return 0; }