#!/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 = (n, m, a, b, c, d) => { let sum_acc = 0n; let max_acc = b * euclid_divmod(d, m)[0]; 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; max_acc = max(max_acc, sum_acc); y_max = (c * (n - 1n) + d) / m; if (y_max == 0n) { return max(max_acc, sum_acc + a * (n - 1n)); } if (a >= 0n) { max_acc = max(max_acc, sum_acc + a * (n - 1n) + b * y_max); } 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 = (l, r, m, a, b, c, d) => { let n = r - l; let q; [q, d] = euclid_divmod(c * l + d, m); return a * l + b * q + mwf(n, m, a, b, c, d); }; const compute_xmin = (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(mid, ared, b, -mred, dred, 0n) <= tdelta) { 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(d, a, b, k).toString()); }