#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
#define inf 0x7fffffff
//#define ll long long
//#define int long long
//#define double long double
#define re int
#define void inline void
#define eps 1e-8
//#define mod 1e9+7
#define ls(p) p<<1
#define rs(p) p<<1|1
#define pi acos(-1.0)
#define pb push_back
#define P pair < int , int >
#define mk make_pair
using namespace std;
const int mod=998244353;
const int M=1e8+5;
const int N=5e5+5;//?????????? 4e8
int n,k=3;
int Xor(int x,int y)
{
	int sum=0,p=1;
	if(y%2==0)  swap(x,y);
	while(x||y)
	{
		sum+=(x%k+k-y%k)%k*p;
		p*=k;
		x/=k;
		y/=k;
	}
	return sum;
}
void solve()
{
	cin>>n>>k;
	int x=0,y=0;
	int op=0;
	for(re i=1;i<=n&&op==0;i++)
	{
		x=Xor(i-1,i-2); 
		if(i==1)  x=0;
		printf("%d\n",x);
		cin>>op;

	}
}
signed main()
{
    int T=1;
//    cout<<Xor(7,6);
    cin>>T;
    for(int index=1;index<=T;index++)
    {
//    	printf("Case #%d: ",index);
        solve();
//        puts("");
    }
    return 0;
}
/*







*/


