// calc sum_{i=0}^{n-1} floor((ai + b) / m) function floor_sum_unsigned(n, m, a, b) { let ans = 0n; while(true) { if (a >= m) { ans += (n * (n - 1n) >> 1n) * (a / m); a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } let y_max = a * n + b; if (y_max < m) { return ans; } [n, b, m, a] = [y_max / m, y_max % m, a, m]; } } function bigint_abs(x) { return x < 0n ? -x : x; } function bigint_min(...args) { return args.reduce((m, e) => e < m ? e : m); } function solve(n, d, m, s) { let pow2s = 1n << s, dm = d * m; if (pow2s != dm) { n = bigint_min(n, d * pow2s / bigint_abs(dm - pow2s)); n -= bigint_abs(floor_sum_unsigned(n + 1n, pow2s, m, 0n) - floor_sum_unsigned(n + 1n, d, 1n, 0n)); } return n; } let input = require("fs").readFileSync("/dev/stdin", "utf8").matchAll(/\b(\d+) (\d+) (\d+) (\d+)/g); for (l of input) { [n, d, m, s] = l.slice(1).map(t=>BigInt(t)); console.log(solve(n, d, m, s).toString()); }