import std.conv, std.functional, std.range, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.mathspecial, std.numeric, std.regex, std.typecons; import core.bitop; class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; } int readInt() { return readToken.to!int; } long readLong() { return readToken.to!long; } string COLOR(string s = "") { return "\x1b[" ~ s ~ "m"; } bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } } bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } } int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; } int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); } int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); } // floor(a / b) Int divFloor(Int)(Int a, Int b) { return a / b - (((a ^ b) < 0 && a % b != 0) ? 1 : 0); } // ceil(a / b) Int divCeil(Int)(Int a, Int b) { return a / b + (((a ^ b) > 0 && a % b != 0) ? 1 : 0); } /* A[i] = K Q[i] + R[i] # op on i: K x[i] + R[i] (0 <= x[i] <= Q[i]) K x[i] + R[i] <= (\sum[j] (K x[j] + R[j])) / K fix s := \sum[j] x[j] x[i] <= floor((s + sumR/K - R[i]) / K) */ long solve(int N, int K, long[] A) { auto Q = new long[N]; auto R = new long[N]; foreach (i; 0 .. N) { Q[i] = A[i] / K; R[i] = A[i] % K; } const sumR = R.sum; if (sumR % K != 0) return -1; const base = sumR / K; long ans = long.max; foreach (v; 0 .. K) { // assume s = K u + v (u >= 0) long need; // <= p u + q alias Entry = Tuple!(long, "u", long, "p", long, "q"); Entry[] es; foreach (i; 0 .. N) { // u + w vs 0, Q[i] const w = divFloor(v + base - R[i], K); chmax(need, 0 - w); es ~= Entry(0 - w, 1, w); es ~= Entry(Q[i] - w, -1, Q[i] - w); } es.sort; const esLen = cast(int)(es.length); long p, q; foreach (j; 0 .. esLen) { p += es[j].p; q += es[j].q; long l = es[j].u; long r = (j + 1 == esLen) ? long.max : (es[j + 1].u - 1); chmax(l, need); // K u + v <= p s + q if (K < p) { chmax(l, divCeil(v - q, p - K)); } else if (K == p) { if (v > q) continue; } else { chmin(r, divFloor(q - v, K - p)); } if (l <= r) { debug writefln("OK u = %s, v = %s", l, v); chmin(ans, base + (K * l + v)); } } } return (ans < long.max) ? ans : -1; } void main() { try { for (; ; ) { const numCases = readInt; foreach (caseId; 0 .. numCases) { const N = readInt; const K = readInt; auto A = new long[N]; foreach (i; 0 .. N) { A[i] = readLong; } const ans = solve(N, K, A); writeln(ans); } } } catch (EOFException e) { } }