#include <bits/stdc++.h>
using namespace std;
const int N=66;
int a[N];
int main()
{
string s="2021ABCD";
for(int i=0;i<s.length();++i)
{
if((s[i]>='0')&&(s[i]<='9'))
a[i]=s[i]-'0';
else
a[i]=s[i]-'A'+10;
}
long long x=0;
for(int i=0;i<s.length();++i)
{
x=x*16+a[i];
}
cout<<x;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b,c,d,e;
int sum;
a=2022;
b=a/1000;
c=a/100%10;
d=a/10%10;
e=a%10;
sum=pow(9,3)*b+pow(9,2)*c+pow(9,1)*d+pow(9,0)*e;
printf("%d",sum);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
const int N=1000;
using ll=long long;
int a[N];
char ch[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
void solve(){
int n,m;cin>>n>>m;
string s;cin>>s;
int len=s.length();
s="#"+s;
for(int i=1;i<=len;i++){
if(s[i]<='9'&&s[i]>='0')a[i]=s[i]-'0';
else a[i]=s[i]-'A'+10;
}
ll x=0;
for(int i=1;i<=len;i++){
x=x*n+a[i];
}
string ans;
while(x){
ans+=ch[x % m];
x/=m;
}
reverse(ans.begin(),ans.end());
cout<<ans<<"\n";
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int t;cin>>t;
while(t--){
solve();
}
return 0;
}