#include #include #include using namespace std; long long s(long long a) { const int mod = 998244353; a %= mod; int inv = 499122177; return a * (a + 1) % mod * inv % mod; } void solve() { const int mod = 998244353; long long n, a; cin >> n >> a; if (a == 1) { cout << s(n - 1) << endl; return; } vector v, d; long long tmp = n, sum = 0; while (tmp > 0) { v.push_back(tmp); d.push_back(sum); sum += tmp % a; ++sum; tmp /= a; } v.push_back(0); long long ans = 0; for (int i = 0; i + 1 < v.size(); ++i) { long long cnt = (v[i] - v[i + 1]) % mod; ans += cnt * d[i] % mod; ans += v[i] % mod * cnt % mod - s(v[i]) + s(v[i + 1]) + mod; ans %= mod; } cout << ans << endl; } int main() { int t; cin >> t; while (t--) solve(); }