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

const int maxn = 2e5 + 5;

int n, k, r;

vector<int> d2k(int x) {
  vector<int> ret;
  while (x) {
    ret.push_back(x % k);
    x /= k;
  }
  return ret;
}

int f(int a, int b) {
  vector<int> va = d2k(a);
  vector<int> vb = d2k(b);
  vector<int> vc(max(va.size(), vb.size()), 0);
  int i = 0;
  while (i < va.size() && i < vb.size()) {
    vc[i] = (va[i] - vb[i] + k) % k;
    i++;
  }
  while (i < va.size()) {
    vc[i] = va[i];
    i++;
  }
  while (i < vb.size()) {
    vc[i] = k - vb[i];
    i++;
  }
  int ret = 0;
  for (int i = vc.size()-1; i >= 0; i--) {
    ret = ret * k + vc[i];
  }
  return ret;
}

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;
}