#include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 998244353; // constexpr int MOD = 1000000007; constexpr int DY4[]{1, 0, -1, 0}, DX4[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}; constexpr int DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T& a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T& a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; void solve() { int n, k; cin >> n >> k; vector a(n); for (ll& a_i : a) cin >> a_i; priority_queue, vector>, greater>> que; ll op = 0, must = 0; REP(i, n) { const ll rem = a[i] % k; op += rem; chmax(must, rem); if (rem < a[i]) que.emplace(rem, i); } if (op % k != 0) { cout << "-1\n"; return; } op /= k; const int threshold = max(n * n * 10, 10000); // 未証明のためTLE対策 for (int counter = 0; op < must; ++counter) { if (que.empty() || counter >= threshold) { cout << "-1\n"; return; } const auto [rem, i] = que.top(); que.pop(); ++op; chmax(must, rem + k); if (rem + k * 2 <= a[i]) que.emplace(rem + k, i); } cout << op << '\n'; } int main() { int t; cin >> t; while (t--) solve(); return 0; }