import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Rubanenko */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CandidateWalk solver = new CandidateWalk(); solver.solve(1, in, out); out.close(); } } class CandidateWalk { void getState(int[] coordinates, int state, int n, int d) { for (int i = 0; i < n; i++) { coordinates[i] = state % d; state /= d; } } long countAnswer(int n, int d) { if (d == 1) { return 0; } int[] deg = new int[n]; deg[0] = 1; for (int i = 1; i < n; i++) { deg[i] = deg[i - 1] * d; } int numberOfStates = 1; for (int i = 1; i <= n; i++) { numberOfStates *= d; } CheckerTools.ensureLimits(numberOfStates, 1, 1 << 16); long[] f = new long[numberOfStates]; Arrays.fill(f, Long.MAX_VALUE); f[0] = 0; int[] coordinates = new int[n]; for (int state = 0; state < numberOfStates; state++) { getState(coordinates, state, n, d); long curSum = 0; long curXor = 0; for (int i = 0; i < n; i++) { curSum += coordinates[i]; curXor ^= coordinates[i]; } for (int i = 0; i < n; i++) { if (coordinates[i] < d - 1) { f[state + deg[i]] = Math.min(f[state + deg[i]], f[state] + (curSum + 1) * (curXor ^ coordinates[i] ^ (coordinates[i] + 1))); } } } return f[f.length - 1]; } public void solve(int testNumber, InputReader in, PrintWriter out) { int testCases = in.nextInt(); CheckerTools.ensureLimits(testCases, 1, 20); for (int test = 1; test <= testCases; test++) { int n = in.nextInt(); int d = in.nextInt(); CheckerTools.ensureLimits(n, 1, 10); out.println(countAnswer(n, d)); } } } class CheckerTools { public static void exit(String message) { System.err.println(message); System.exit(1); } public static void ensureCondition(boolean condition, String message) { if (!condition) { exit(message); } } public static void ensureLimits(long n, long l, long r) { if (n < l ||n > r) { ensureCondition(l <= n && n <= r, "Number " + Long.toString(n) + " is out of range [" + Long.toString(l) + ", " + Long.toString(r) + "]"); } } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } public String nextLine() { String line = null; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }