#include<bits/stdc++.h>
using namespace std;
vector<int> get_smallest_prime(int n_max) {
vector<int> sp(n_max);
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() {
int n_max = 4e5;
vector<int> sp = get_smallest_prime(n_max);
vector<int> primes;
for(int i = 2; i < n_max; 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(n_max, vector<int>(2, inf));
vector<vector<bool>> vis(n_max, vector<bool>(2));
queue<pair<int, int>> q;
vis[n][0] = true;
dis[n][0] = 0;
q.push({n, 0});
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(!vis[sp[s]][parity ^ 1]) {
vis[sp[s]][parity ^ 1] = true;
dis[sp[s]][parity ^ 1] = dis[x][parity] + 1;
q.push({s, parity ^ 1});
}
}
}
int best = 0;
for(int i = (int)primes.size() - 1; 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(!vis[primes[i]][p]) {
continue;
}
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;
}
}