typedef long long ll; typedef long double ld; #include using namespace std; int main() { ll q; std::cin >> q; for (int i = 0; i < q; i++) { ll a,b,c; std::cin >> a>>b>>c; if(c==1){ std::cout << -1 << std::endl; continue; } ll cnt = 0; while(a%c>0||a/c>0){ if(a%c!=0)cnt++; if(a/c!=0)cnt++; if(a%c!=0&&a%c<=c-2&&a/c%c==1)cnt--; a/=c; } std::cout << cnt*b << std::endl; } }