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

int k;

int addk(int a,int b)
{
	int base,aw,bw,ret=0;
	for(base=1;base<=max(a,b);base*=k)
	{
		aw=a/base%k;
		bw=b/base%k;
		ret+=(aw+bw)%k*base;
	} 
	return ret;
}

int subk(int a,int b)
{
	int base,aw,bw,ret=0;
	for(base=1;base<=max(a,b);base*=k)
	{
		aw=a/base%k;
		bw=b/base%k;
		ret+=(aw-bw+k)%k*base;
	} 
	return ret;
}

int main()
{
	int T,n,y,i,r;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d%d",&n,&k);
		for(i=0;i<n;i++)
		{
			if(i==0)
				y=0;
			else if(i&1)
				y=subk(i-1,i);
			else
				y=subk(i,i-1);
			printf("%d\n",y);
			fflush(stdout);
			scanf("%d",&r);
			if(r==1)
				break;
		}
	}
}

