#include<bits/stdc++.h>
using namespace std;
vector<int> get_smallest_prime(int n_max) {
vector<int> sp(n_max + 1);
sp[1] = 1;
for(int i = 2; i <= n_max; i++) {
for(int j = i; j <= n_max; j += i) {
if(!sp[j])
sp[j] = i;
}
}
return sp;
}
int main() {
vector<int> sp = get_smallest_prime(4e5);
vector<int> primes;
for(int i = 2; i <= 390000; i++) {
if(sp[i] == i) {
primes.push_back(i);
}
}
int tc;
cin >> tc;
while(tc--) {
int n, m, k;
cin >> n >> m >> k;
const int inf = 1e9;
vector<vector<int>> dis(4e5, vector<int>(2, inf));
queue<pair<int, int>> q;
for(int s = max(2, n - m); s <= n + m; s++) {
if(s == n) {
continue;
}
if(dis[sp[s]][1] == inf) {
dis[sp[s]][1] = 1;
q.push({s, 1});
}
}
while(!q.empty()) {
pair<int, int> top = q.front();
q.pop();
int x = top.first, parity = top.second;
for(int s = max(2, x - m); s <= x + m; s++) {
if(s == x) {
continue;
}
if(dis[sp[s]][parity ^ 1] > dis[x][parity] + 1) {
dis[sp[s]][parity ^ 1] = dis[x][parity] + 1;
q.push({s, parity ^ 1});
}
}
}
int best = 0;
for(int i = (int)primes.size(); i >= 0; i--) {
bool has_cycle = false;
if(i + 1 < primes.size() && primes[i + 1] - primes[i] <= m) {
has_cycle = true;
}
if(i > 0 && primes[i] - primes[i - 1] <= m) {
has_cycle = true;
}
for(int p = 0; p < 2; p++) {
if(dis[primes[i]][p] == k) {
// cout << "pr: " << primes[i] << " p: " << p << " d: " << dis[primes[i]][p] << endl;
best = max(best, primes[i]);
}
else if(has_cycle && dis[primes[i]][p] < k && (k - dis[primes[i]][p]) % 2 == 0) {
// cout << "pr: " << primes[i] << " p: " << p << " d: " << dis[primes[i]][p] << endl;
best = max(best, primes[i]);
}
}
}
cout << best << endl;
}
}