#include<bits/stdc++.h> using namespace std; #define rep(i,x,y) for(int i=x;i<y;i++) #define range(a) (a).begin(),(a).end() #define print(A,n) rep(i,0,n){cout<<(i ? " ":"")<<A[i];}cout<<endl; #define pprint(A,m,n) rep(j,0,m){print(A[j],n);} const long mod=1e9+7; const int size=1e5; const int INF=1e9; int main(){ int Q;cin>>Q; long a,b,c; rep(i,0,Q){ cin>>a>>b>>c; long res=0; if(c==1){ cout<<-1<<endl; continue; } while(a>0){ if(a<c){ res++; break; } else if(a<2*c-1){ res+=2; break; } else if(a%c==0) res++; else res+=2; a=a/c; }cout<<res*b<<endl; } }