#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
ll gcd(ll a, ll b) {
return !b ? a : gcd(b, a%b);
}
bool check(ll x) {
if(x <= 10) return false;
string s1 = "";
while(x) {
s1 += x%10 + '0';
x /= 10;
}
reverse(s1.begin(), s1.end());
int n = s1.length();
string s2 = s1.substr(0, (n+1)/2);
string s3 = s1.substr((n+1)/2);
ll a = 0, b = 0;
for(int i=0; i<s2.length(); ++i)
a = a*10 + s2[i] - '0';
for(int i=0; i<s3.length(); ++i)
b = b*10 + s3[i] - '0';
return gcd(a, b) == 1;
}
int main() {
ll a, b, c;
int t; scanf("%d", &t);
while(t--) {
scanf("%lld%lld", &a, &b);
c = -1;
for(ll i=b; i>=a; --i) {
if(check(i)) {
c = i;
break;
}
}
printf("%lld\n", c);
}
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdHlwZWRlZiBsb25nIGxvbmcgbGw7CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgpsbCBnY2QobGwgYSwgbGwgYikgewoJcmV0dXJuICFiID8gYSA6IGdjZChiLCBhJWIpOwp9Cgpib29sIGNoZWNrKGxsIHgpIHsKCWlmKHggPD0gMTApIHJldHVybiBmYWxzZTsKCXN0cmluZyBzMSA9ICIiOwoJd2hpbGUoeCkgewoJCXMxICs9IHglMTAgKyAnMCc7CgkJeCAvPSAxMDsKCX0KCXJldmVyc2UoczEuYmVnaW4oKSwgczEuZW5kKCkpOwoJaW50IG4gPSBzMS5sZW5ndGgoKTsKCXN0cmluZyBzMiA9IHMxLnN1YnN0cigwLCAobisxKS8yKTsKCXN0cmluZyBzMyA9IHMxLnN1YnN0cigobisxKS8yKTsKCWxsIGEgPSAwLCBiID0gMDsKCWZvcihpbnQgaT0wOyBpPHMyLmxlbmd0aCgpOyArK2kpCgkJYSA9IGEqMTAgKyBzMltpXSAtICcwJzsKCWZvcihpbnQgaT0wOyBpPHMzLmxlbmd0aCgpOyArK2kpCgkJYiA9IGIqMTAgKyBzM1tpXSAtICcwJzsKCXJldHVybiBnY2QoYSwgYikgPT0gMTsKfQoKaW50IG1haW4oKSB7CglsbCBhLCBiLCBjOwoJaW50IHQ7IHNjYW5mKCIlZCIsICZ0KTsKCXdoaWxlKHQtLSkgewoJCXNjYW5mKCIlbGxkJWxsZCIsICZhLCAmYik7CgkJYyA9IC0xOwoJCWZvcihsbCBpPWI7IGk+PWE7IC0taSkgewoJCQlpZihjaGVjayhpKSkgewoJCQkJYyA9IGk7CgkJCQlicmVhazsKCQkJfQoJCX0KCQlwcmludGYoIiVsbGRcbiIsIGMpOwoJfQoJcmV0dXJuIDA7Cn0=