#define _CRT_SECURE_NO_WARNINGS #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; typedef string::const_iterator State; #define Ma_PI 3.141592653589793 #define eps 1e-5 #define LONG_INF 2000000000000000000LL #define GOLD 1.61803398874989484820458 #define MAX_MOD 1000000007LL #define GYAKU 500000004LL #define MOD 998244353LL #define seg_size 262144*2 #define REP(a,b) for(long long a = 0;a < b;++a) int main() { int query; cin >> query; REP(te, query) { long long a, b, c; cin >> a >> b >> c; vector inputs; while (a != 0) { inputs.push_back(a % c); a /= c; } reverse(inputs.begin(), inputs.end()); long long ans = inputs.size()-1; for (int i = 0; i < inputs.size(); ++i) { if (inputs[i])ans++; } for (int i = 1; i < inputs.size()-1; ++i) { if (inputs[i - 1] == 1 && inputs[i] != 0) { ans--; i++; } } cout << ans * b << endl; } }