#include using namespace std; typedef long long ll; #define F first #define S second #define pii pair #define eb emplace_back #define all(v) v.begin(), v.end() #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep3(i, l, n) for (int i = l; i < (n); ++i) #define sz(v) (int)v.size() #define inf (int)(1e9+7) template inline bool chmin(T1 &a, T2 b) { if (a > b) { a = b; return 1; } return 0; } template inline bool chmax(T1 &a, T2 b) { if (a < b) { a = b; return 1; } return 0; } template T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); } // https://babcs2035.hateblo.jp/entry/2019/10/26/yukicoder%EF%BC%9ANo.915_Plus_Or_Multiple_Operation int main() { ios::sync_with_stdio(false); cin.tie(0); int q; cin >> q; while (q--) { int a, b, c; cin >> a >> b >> c; if (c == 1) { cout << -1 << endl; continue; } int cnt = 0, t = a; ll ans = 1e18; while (t) { if (t % c == 0) { t /= c; cnt++; } else { // 最後の方, 積より和のほうがいいことがある // 毎回確かめとく chmin(ans, cnt + (t + c - 2) / (c - 1)); t -= t % c; ++cnt; } } chmin(ans, cnt); cout << (ll)ans * b << endl; } }