#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
typedef pair<long long,long long>pll;
int k;
int query(int x,int f){
    int y=x-1,ans=0,v=1;
    while(x||y){
        if(!f) ans+=v*((x%k+k-y%k)%k);
        else ans+=v*((y%k+k-x%k)%k);
        x/=k,y/=k;
        v*=k;
    }
    return ans;
}
void solve(){
    int n,i,t;
    scanf("%d%d",&n,&k);
    for(i=0;i<n;i++){
        t=i?query(i,i%2):0;
        printf("%d\n",t),fflush(stdout);
        scanf("%d",&t);
        if(t==1) break;
    }
}
int main(void){
    int T=1;
    cin>>T;
    while(T--){
        solve();
    }
}