传送门
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define debug cout<<"debug"<<endl
mt19937 rd(time(0));
typedef long long ll;
typedef long double ld;
typedef pair<int, int> PII;
const double eps = 1e-8;
const double PI = 3.14159265358979323;
const int N = 1e5+10, M = 2*N, mod = 1e9+7;
const int INF = 0x3f3f3f3f;
int n, m;
int a[N], cnt[N]; // 用cnt[i]来表示当前区间内i的倍数的数量
int sum; // sum表示当前区间内有多少数能被解决
// 用双指针来枚举最小的a[l], 找到最小的r使得sum == m, 当前区间答案即为res = min(res, a[r]-a[l]);
void add(int x)
{
for(int i = 1; i<=x/i; i++)
{
if(x%i == 0)
{
if(i<=m)
{
if(++cnt[i] == 1) sum++;
}
if(x/i<=m && i*i != x)
{
if(++cnt[x/i] == 1) sum++;
}
}
}
}
void del(int x)
{
for(int i = 1; i<=x/i; i++)
{
if(x%i == 0)
{
if(i<=m)
{
if(--cnt[i] == 0) sum--;
}
if(x/i<=m && i*i != x)
{
if(--cnt[x/i] == 0) sum--;
}
}
}
}
void solve()
{
cin>>n>>m;
sum = 0;
for(int i = 1; i<=m; i++) cnt[i] = 0;
for(int i = 1; i<=n; i++) cin>>a[i];
sort(a+1, a+1+n);
int res = INF;
for(int i = 1, j = 1; i<=n; i++)
{
del(a[i-1]);
while(j<=n && sum<m) add(a[j++]);
if(sum == m) res = min(res, a[j-1]-a[i]);
}
if(res == INF) cout<<-1<<endl;
else cout<<res<<endl;
}
int main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int T;
T = 1;
cin>>T;
while(T -- )
{
solve();
}
return 0;
}