#include using namespace std; template ostream &operator<<(ostream &s, const pair &v) { s << "(" << v.first << ", " << v.second << ")"; return s; } template requires (!is_convertible_v) istream &operator>>(istream &s, T &&v) { for (auto &&x : v) s >> x; return s; } template requires (!is_convertible_v) ostream &operator<<(ostream &s, T &&v) { for (auto &&x : v) s << x << ' '; return s; } #ifdef LOCAL template void dbg(T... x) { char e{}; ((cerr << e << x, e = ' '), ...); } #define debug(x...) dbg(#x, '=', x, '\n') #else #define debug(...) ((void)0) #endif #define all(v) (v).begin(), (v).end() #define rall(v) (v).rbegin(), (v).rend() #define ff first #define ss second template inline constexpr T inf = numeric_limits::max() / 2; bool chmin(auto &a, auto b) { return (b < a and (a = b, true)); } bool chmax(auto &a, auto b) { return (a < b and (a = b, true)); } using u32 = unsigned int; using i64 = long long; using u64 = unsigned long long; using i128 = __int128; using u128 = unsigned __int128; constexpr i64 mod = 998244353; void solve() { int n, k; cin >> n >> k; vector A(n); cin >> A; const i64 sum = reduce(all(A), 0LL); if (sum % k != 0) { cout << -1 << '\n'; return; } auto check1 = [&](i64 t) -> bool { i64 rem = t * k; i64 s = 0; for (i64 x : A) { if (x % k > t) { return false; } rem -= x % k; s += min((t - x % k) / k, x / k); } if (rem < 0 or rem > s * k) { return false; } return true; }; auto check2 = [&](i64 t) -> bool { i64 rem = t * k; i64 s = 0; for (i64 x : A) { if (x % k > t) { return false; } rem -= x % k; s += (t - x % k) / k; } if (rem < 0 or rem > s * k) { return false; } return true; }; const i64 upper = sum / k; i64 ans = inf; for (i64 r = 0; r < k; r++) { i64 p = *ranges::partition_point( views::iota(0, upper / k + 1), [&](i64 x) { return !check2(r + x * k); } ); if (check1(r + p * k)) { chmin(ans, r + p * k); } } if (ans == inf) { ans = -1; } cout << ans << '\n'; } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); int t = 1; cin >> t; while (t--) { solve(); } return 0; }