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


// a - b = c
int bitwDelete(int a, int b, int k) {
    int N = 20;
    vector<int> bit(N, k);
    int A = a, B = b;
    int i = 0;
    while(A > 0) {
        bit[i++] += A % k;
        A /= k;
    }
    i = 0;
    while(B > 0) {
        bit[i++] -= B % k;
        B /= k;
    }
    /*
    for(int j = 0; j < bit.size(); ++j) {
        cout << bit[j] << " ";
    }
    cout << endl;
    */
    int ans = 0;
    i = N - 1;
    for(; i >= 0; --i) {
        if(bit[i] % k != 0) {
            break;
        }
    }
    while(i >= 0) {
        ans = ans * k + (bit[i--] % k);
    }
    return ans;

}

// a + b = c
int bitwAdd(int a, int b, int k) {
    int N = 20;
    vector<int> bit(N, k);
    int A = a, B = b;
    int i = 0;
    while(A > 0) {
        bit[i++] += A % k;
        A /= k;
    }
    i = 0;
    while(B > 0) {
        bit[i++] += B % k;
        B /= k;
    }
    /*
    for(int j = 0; j < bit.size(); ++j) {
        cout << bit[j] << " ";
    }
    cout << endl;
    */
    int ans = 0;
    i = N - 1;
    for(; i >= 0; --i) {
        if(bit[i] % k != 0) {
            break;
        }
    }
    while(i >= 0) {
        ans = ans * k + (bit[i--] % k);
    }
    return ans;

}

int main() {
    int T;
    cin >> T;
    for (int q = 0; q < T; ++q)
    {

        int n, k, f = 0;
        cin >> n >> k;
        
        for(int i = 0; i < n; ++i) {
            
            int next;
            if(i == 0) {
                next = 0;
            }
            else if((i+1) % 2 == 0) {
                next = bitwDelete(i-1, i, k);
            }
            else {
                next = bitwDelete(i, i-1, k);
            }
            cout << next << endl;
            
            int r;
            fflush(stdout);
            cin >> r;
            if(r == 1) {
                break;
            }
        }
        
       
        
    }
    return 0;
}