import std.stdio, std.conv, std.string, std.bigint;
import std.math, std.random, std.datetime;
import std.array, std.range, std.algorithm, std.container, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

void main(){
	int t = read.to!int;
	int b = read.to!int;
	
	long[] ns;
	foreach(i; 0 .. t) ns ~= read.to!long;
	
	foreach(n; ns){
		int[] xs = f(n, -b);
		for(int i = 0; i < xs.length; i ++){
			debug writeln("xs:", xs);
			if(i % 2 == 0) continue;
			else{
				// [..., x, ...] を [..., (-b - x), 1, ...] に変換
				int x = xs[i];
				if(x == 0) continue;
				xs[i] = -b - x;
				for(int j = i + 1; j <= n; j ++){
					if(j == xs.length){
						xs ~= 1;
						break;
					}
					else if(xs[j] < -b - 1){
						xs[j] += 1;
						break;
					}
					else{
						xs[j] = 0;
						continue;
					}
				}
			}
		}
		string ans = "";
		foreach_reverse(x; xs) ans ~= x.to!string;
		
		if(ans == "") ans = "0";
		
		ans.writeln;
	}
}

// nを通常のb進で表したもの(1のけたから順に)
int[] f(long n, int b){
	int[] res;
	long x = n;
	while(x > 0){
		res ~= x % b;
		x /= b;
	}
	return res;
}