#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const int MAXN=2e7+3;
short a[MAXN],b[MAXN];
int k;
int Xo(int x,int y)
{
    int toa=0,tob=0;
    while(x)
    {
        a[++toa]=x%k;
        x/=k;
    }
    while(y)
    {
        b[++tob]=y%k;
        y/=k;
    }
    a[toa+1]=b[tob+1]=0;
    int ans=0;
    for(int i=max(toa,tob);i;--i)
    {
        ans*=k;
        ans+=(k+a[i]-b[i])%k;
    }
    return ans;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n>>k;
        int r;
        for(int i=0;i<n;++i)
        {
            if(i==0)cout<<0<<endl;
            else if(i&1)cout<<Xo(i-1,i)<<endl;
            else cout<<(Xo(i,i-1))<<endl;
            cout.flush();
            cin>>r;
            if(r==1)break;
        }
    }
    return 0;
}