#include <bits/stdc++.h>

using namespace std;

int k;
int sum(int x, int y) {
    int pwr=1;
    int ret=0;
    while(x||y) {
        ret+=pwr*((y+x)%k);
        pwr*=k;
        x/=k;
        y/=k;
    }
    return ret;
}
int neg(int x, int y) {
    int pwr=1;
    int ret=0;
    while(x||y) {
        ret+=pwr*((x%k+(k-y%k)%k)%k);
        pwr*=k;
        x/=k;
        y/=k;
    }
    return ret;
}

int main() {
    int tc=1;
    scanf("%d",&tc);
    while(tc--) {
        int n;
        cin>>n>>k;
        int s=0,cur=0,x=0;
        for(int f=0;f<n&&!x;f++) {
            if(f%2)
                cur = neg(s,f);
            else
                cur=sum(s,f);
            cout<<cur<<endl;
            cout.flush();
            s=neg(cur,s);
            cin>>x;
        }
    }
}
