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

int T,N,K;

int kxor (int a, int b, int k)
{
    int nout = 0;
    int ind = 0;
    while (a || b)
    {
        int ai = a % k, bi = b % k;
        nout += (ai + bi) % k;
        a /= k, b /= k;
        nout *= k, ind++;
    }
    nout /= k;

    int out = 0;
    for (int i = 0; i < ind; i++)
    {
        out += nout % k;
        out *= k, nout /= k;
    }
    return out/k;
}

int knxor (int a, int b, int k)
{
    int nout = 0;
    int ind = 0;
    while (a || b)
    {
        int ai = a % k, bi = b % k;
        nout += (ai - bi + k) % k;
        a /= k, b /= k;
        nout *= k, ind++;
    }
    nout /= k;

    int out = 0;
    for (int i = 0; i < ind; i++)
    {
        out += nout %k;
        out *= k, nout /= k;
    }
    return out/k; 
}

void solve (void)
{
    cin >> N >> K;

    int p = 0;
    for (int i = 0; i < N; i++)
    {
        int guess;
        if ((i+1)&1) guess = kxor (p, i, K);
        else guess = knxor (p, i, K);
        cout << guess << endl;

        int resp; cin >> resp;
        if (resp == -1) return;
        if (resp) return;

        p = knxor (guess, p, K);
    }

    //this is very bad if we get here
    assert (false);
}

int main (void)
{
    cin >> T;
    while (T--)
    {
        solve();
    }
}
