//include //------------------------------------------ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define SHOW_VECTOR(v) {std::cerr << #v << "\t:";for(const auto& xxx : v){std::cerr << xxx << " ";}std::cerr << "\n";} #define SHOW_MAP(v){std::cerr << #v << endl; for(const auto& xxx: v){std::cerr << xxx.first << " " << xxx.second << "\n";}} using LL = long long; //------------------------------------------ //------------------------------------------ int main() { int Q; cin >> Q; while (Q--) { LL A, B, C; cin >> A >> B >> C; if (C == 1) { cout << -1 << endl; continue; } string ans = ""; LL cnt = 1; while (A != 0) { if (A > C && A <= 2 * C) { cnt += 2; if (A != 2 * C)cnt++; break; } if (A % C == 0) ans += '0'; else ans += '1'; A /= C; } reverse(ans.begin(), ans.end()); for (int i = 1; i < ans.size(); i++) { if (ans[i] != '0')cnt++; cnt++; } cout << cnt * B << endl; } return 0; }