#include "bits/stdc++.h" using namespace std; using ll = long long; using pii = pair; using pll = pair; using vi = vector; using vl = vector; using vvi = vector; using vvl = vector; const ll INF = 1LL << 60; const ll MOD = 1000000007; template bool chmax(T &a, const T &b) { return (a < b) ? (a = b, 1) : 0; } template bool chmin(T &a, const T &b) { return (b < a) ? (a = b, 1) : 0; } template void print(const C &c, std::ostream &os = std::cout) { std::copy(std::begin(c), std::end(c), std::ostream_iterator(os, " ")); os << std::endl; } int main() { int q; cin >> q; vl a(q), b(q), c(q); for (int i = 0; i < q; ++i) { cin >> a[i] >> b[i] >> c[i]; } for (int i = 0; i < q; ++i) { ll ret = 0; if (c[i] == 1) { cout << -1 << "\n"; continue; } while (a[i] > 0) { if ((a[i] / c[i]) % c[i] == 1 && a[i] % c[i] < c[i] - 1 && a[i] % c[i] != 0) { ret++; a[i] -= c[i]; } if (a[i] % c[i] != 0) ret++; a[i] /= c[i]; ret++; } cout << (ret - 1LL) * b[i] << "\n"; } return 0; }