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

const int maxn = 2e5 + 5;

int n, k, r;


int f(int x, int y) {
  int z=0;
  int p=1;
  while(x>0 || y>0)
  {
      int a=x%k;
      x=x/k;
      int b=y%k;
      y=y/k;
      int c=(a-b+k)%k;
      z=z+p*c;
      p=p*k;
  }
  return z;
}

void solve() {
  cout << "0" << endl;
  cin >> r;
  if (r == 1) return;

  for (int i = 1; i < n; i++) {
    int q;
    if (i % 2 == 1) {
      q = f(i-1, i);
    } else {
      q = f(i, i-1);
    }
    cout << q << endl;
    cin >> r;
    if (r == 1) return;
  }
}

int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> k;
    solve();
  }
  return 0;
}