#include <bits/stdc++.h>
using namespace std;

//.define
// #define FILE_IN_OUT
#define RET(_x) cout << (_x) << '\n'; return;
#define all(_obj) (_obj).begin(), (_obj).end()
#define loop(_n) for (int i = 0; i < (_n); ++i)
#define sz(_obj) static_cast<int>((_obj).size())
#ifdef SHJ_LOCAL
#define debug(_x) std::cerr << (#_x) << " = " << (_x) << '\n' << std::flush;
#else
#define debug(_x) {}
#endif
#define endl "\n"
template <typename P, typename Q>
P CeilDiv(P _dividend, Q _divider) {
    return static_cast<P>((_dividend - 1LL + _divider) / _divider);
}
template <typename Tp>
inline void outarr(Tp _begin, Tp _end, const char* _delim = " ") {
    for (Tp current = _begin; current != _end; ++current) {
        std::cout << *current << _delim;
    }
    std::cout << '\n';
}

//.constant
using ll = long long;
using pii = std::pair<int, int>;
constexpr int INF = 0x3f3f3f3f;
constexpr int MOD = static_cast<int>(1e9 + 7);

//.data
int Add(int x, int y, int m) {
    int res = 0;
    int t = 1;
    while (x > 0 || y > 0) {
        const int a = x % m;
        x /= m;
        const int b = y % m;
        y /= m;
        res += (a + b) % m * t;
        t *= m;
    }
    return res;
}

int Sub(int x, int y, int m) {
    int res = 0;
    int t = 1;
    while (x > 0 || y > 0) {
        const int a = x % m;
        x /= m;
        const int b = y % m;
        y /= m;
        res += (a - b + m) % m * t;
        t *= m;
    }
    return res;
}

int Ask(int x) {
    cout << x << endl << flush;
    int res;
    cin >> res;
    return res;
}

//.code
void SolveTask() {
    int n, k;
    cin >> n >> k;
    int cur = 0;
    loop(n) {
        const int y = i & 1 ? Sub(cur, i, k) : Add(cur, i, k);
        if (Ask(y)) {
            return;
        }
        cur = Sub(y, cur, k);
    }
}

int main() {
#ifdef FILE_IN_OUT
    std::ifstream cin("input.txt", std::ios::in);
    std::ofstream cout("output.txt", std::ios::out);
#else
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
#endif
    int test_cases = 1;
    cin >> test_cases;
    for (int yt = 1; yt <= test_cases; ++yt) {
        SolveTask();
    }
#ifdef FILE_IN_OUT
    cin.close();
    cout.close();
#endif
    return 0;
}