// time-limit: 5000
// problem-url: https://codeforces.com/contest/1543/problem/D1
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <set>
#include <map>
#include <array>
#include <random>
#include <cmath>
#include <chrono>
#include <list>
#include <ctime>
#include <sstream>
#include <queue>
#include <climits>
#include <stack>
#include <random>
#include <bitset>
#include <numeric>
#include <cassert>
using namespace std;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef long long ll;
#define rep(x, b, e) for(int x=(b); x<(e); ++x)
#define trav(a, x) for(auto& a : x)
#define ford(x, b, e) for(int x=((int)(b))-1; x>=(e); --x)
#define all(c) c.begin(),c.end()
#define sz(x) ((int)((x).size()))
#define pb push_back
#define eb emplace_back
#define st first
#define nd second
#define mp(x,y) make_pair(x,y)
typedef short int sint;

#define what_is(x) cerr << #x << " is " << x << endl;


mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // use rng() to get unsigned int
// mt19937_64 for random long longs

int k;
vi rozloz(int x) {
	vi res;
	while (x) {
		res.pb(x % k);
		x /= k;
	}
	return res;
}

vi polacz(vi a, vi b) {
	int roz = max(sz(a), sz(b));
	vi c(roz);
	rep(i, 0, roz) {
		if (i < sz(a)) {
			c[i] += a[i];
		}	
		if (i < sz(b)) {
			c[i] = (c[i] + b[i]) % k;
		}
	}
	return c;
}

int zloz(vi a) {
	int res = 0;
	ford(i, sz(a), 0) {
		res *= k;
		res += a[i];
	}
	return res;
}

void solve() {
	int n;
	cin >> n >> k;
	vi my_xor;
	rep(i, 0, n) {
		// cout << i ^ (my_xor) << endl;
		cout << zloz(polacz(rozloz(i), my_xor))  << endl;
		int x;
		cin >> x;
		if (x == 1) {
			// printf("returning\n");
			return;
		} else {
			// my_xor ^= (i ^my_xor);
			my_xor = polacz( my_xor, polacz(rozloz(i), my_xor) );
		}
	}
}

int main() {
	ios_base::sync_with_stdio(false); cin.tie(0);
	int t;
	cin >> t;
	// t = 1;
	while (t--) {
		solve();
	}
}