#!/usr/bin/env nodejs const gcd = (a, b) => { while (b != 0n) { [a, b] = [b, a % b]; } return a; }; const max = (a, b) => { return a < b ? b : a; }; const euclid_divmod = (a, b) => { let [q, r] = [a / b, a % b]; if (r < 0) { if (b > 0) { q = q - 1n; r = r + b; } else { q = q + 1n; r = r - b; } } return [q, r]; }; const mwf_leq = (z, n, m, a, b, c, d) => { let sum_acc = -z; let q, y_max; while (true) { [q, c] = euclid_divmod(c, m); a = a + b * q; [q, d] = euclid_divmod(d, m); sum_acc = sum_acc + b * q; if (sum_acc > 0n) { return false; } y_max = (c * (n - 1n) + d) / m; if (y_max == 0n) { return sum_acc + a * (n - 1n) <= 0n; } if (sum_acc + max(a * (n - 1n), 0n) + max(b * y_max, 0n) <= 0n) { return true; } if (a >= 0n) { if (sum_acc + a * (n - 1n) + b * y_max > 0n) { return false; } } else { sum_acc = sum_acc + a + b; } [n, m, a, b, c, d] = [y_max, c, b, a, m, m - d - 1n]; } }; const mwf_lr_leq = (z, l, r, m, a, b, c, d) => { let n = r - l; let q; [q, d] = euclid_divmod(c * l + d, m); return mwf_leq(z - a * l - b * q, n, m, a, b, c, d); }; const compute_xmin_leq = (d, a, b, k) => { let gcd_da = gcd(d, a); let [dred, ared] = [d / gcd_da, a / gcd_da]; let [mred, rred] = euclid_divmod(ared * b, dred); let tdelta = b * k; if (rred == 0n && dred * k + 1n >= ared) { return -1n; } let [lo, hi] = [0n, ared * b * k + 2n]; while (lo + 1n < hi) { let mid = (lo + hi) / 2n; if (mwf_lr_leq(tdelta, lo, mid, ared, b, -mred, dred, 0n)) { lo = mid; } else { hi = mid; } } return d * lo; }; let [t, ...inputs] = require("fs") .readFileSync("/dev/stdin", "utf8") .trim() .split(/\s+/); t = Number(t); for (let i = 0; i < t; i += 1) { let [d, a, b, k] = inputs.slice(i * 4, i * 4 + 4).map((s) => BigInt(s)); console.log(compute_xmin_leq(d, a, b, k).toString()); }