// calc sum_{i=0}^{n-1} floor((ai + b) / m) function floor_sum_unsigned(n, m, a, b) { let x = 0n; while(n > 0n) { x += a / m * (n * (n - 1n) >> 1n) + b / m * n; a %= m; b = a * n + b % m; [n, b, m, a] = [b / m, b % m, a, m]; } return x; } function bigIntMin(...args) { return args.reduce((m, e) => e < m ? e : m); } function bigIntAbsDiff(a, b) { return a < b ? b - a : a - b; } function solve(n, d, m, s) { let t = 1n << s, u = d * m; if (t != u) { n = bigIntMin(n, (d * t - 1n) / bigIntAbsDiff(t, u)); n -= bigIntAbsDiff( floor_sum_unsigned(n + 1n, t, m, 0n), floor_sum_unsigned(n + 1n, d, 1n, 0n), ); } return n; } let [q, ...inputs] = require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\s+/); q = Number(q); let q4 = q * 4; for (let i = 0; i < q4; i += 4) { console.log(solve.apply(null, inputs.slice(i, i + 4).map(s=>BigInt(s))).toString()); }