#include using namespace std; void print(vector& v){ for(int i = v.size()-1; 0 <= i; --i) cout << v[i] << " "; cout << endl; } int main() { int Q; cin >> Q; while(Q--){ long long A,B,C; cin >> A >> B >> C; 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; ans += (int)v.size() - 1; for(int i = 0; i < v.size(); ++i) if(v[i]) ans += 1; cout << ans*B << endl; } return 0; }