#include #include using namespace std; typedef long long ll; ll solve(int a, int b, int c) { if (c == 1) { return -1; } // cerr << a << " " << b << " " << c << endl; ll ret = 0; int tmp = a; while (tmp > 0) { // cerr << tmp << " "; if (tmp < 2*c-1) { tmp -= c-1; } else if (tmp % c == 0) { tmp /= c; } else { tmp -= tmp%c; } ret += 1; } // cerr << endl; // cerr << ret << endl; return ret*(ll)b; } int main() { int q; cin >> q; for (int i = 0; i < q; ++i) { int a, b, c; cin >> a >> b >> c; ll ans = solve(a, b, c); cout << ans << endl; } }