#include <iostream>
using namespace std;
int len;
char test[11][1000][10];
int ChuyenSangSo(char c[10]) {
int num = 0;
for (int i = 0; i < len; i++) {
num = num * 10 + (c[i] - '0');
}
return num;
}
void ChuyenSangChar(char b[10], int i, int j, int m) {
//char b[10];
int l = len;
while (m != 0) {
char e = m % 10 + '0';
l--;
b[l] = e;
m /= 10;
}
}
bool kt(int i, int j) {
for (int x = 0; x < len; x++) {
if (test[i][j][x] == NULL)
return false;
}
return true;
}
bool CheckTrung(int number[11][1000], int i, int j, int n) {
for (int y = 0; y < j; y++) {
if (number[i][y] == n) {
return false;
}
}
return true;
}
int main() {
int t;
cin >> t;
for (int tc = 1; tc <= t; tc++) {
char a[10];
int n;
len = 0;
cin >> a >> n;
for (int i = 0; i < 10; i++) {
if (a[i] == NULL)
break;
else
len++;
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 1000; j++) {
for (int z = 0; z < 10; z++) {
test[i][j][z] = NULL;
}
}
}
for (int i = 0; i < len; i++) {
test[0][0][i] = a[i];
}
int number[11][1000];
number[0][0] = ChuyenSangSo(a);
int jj = 0;
for (int i = 0; i < n; i++) {
int j = 0;
jj = 0;
//cout << i + 1 << endl;
while (kt(i, j)) {
char b[10];
for (int ii = 0; ii < len; ii++) {
b[ii] = test[i][j][ii];
}
for (int x = 0; x < len - 1; x++) {
for (int y = x + 1; y < len; y++) {
char temp = b[x];
b[x] = b[y];
b[y] = temp;
int num = ChuyenSangSo(b);
if (CheckTrung(number, i + 1, jj, num)) {
//cout << num << endl;
for (int ii = 0; ii < len; ii++) {
test[i + 1][jj][ii] = b[ii];
}
//cout << test[i + 1][jj] << endl;
number[i + 1][jj] = num;
jj++;
}
for (int ii = 0; ii < len; ii++) {
b[ii] = test[i][j][ii];
}
}
}
j++;
}
}
int max = 0;
for (int j = 0; j < jj; j++) {
if (number[n][j] > max) {
max = number[n][j];
}
}
cout << "Case #" << tc << endl << max << endl;
}
}