#include // assert #include // cin, cout, ios #include // swap #include namespace mp = boost::multiprecision; using bigint = mp::cpp_int; bigint floor_sum(bigint n, bigint m, bigint a, bigint b) { assert(n >= 0 && m > 0); bigint x = 0, q; if(a < 0) { mp::divide_qr(a, m, q, a); if(a < 0) { q -= 1; a += m; } x += q * (n * (n - 1) >> 1); } if(b < 0) { mp::divide_qr(b, m, q, b); if(b < 0) { q -= 1; b += m; } x += q * n; } while(n > 0) { mp::divide_qr(a, m, q, a); x += q * (n * (n - 1) >> 1); mp::divide_qr(b, m, q, b); x += q * n; mp::divide_qr(a * n + b, m, n, b); std::swap(a, m); } return x; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); int q, s; bigint n, d, m, t, u; std::cin >> q; for(int i = 0; i < q; i++) { std::cin >> n >> d >> m >> s; t = (bigint)1 << s, u = d * m; if (t != u) { n = mp::min(n, d * t / mp::abs(t - u)); n -= mp::abs(floor_sum(n + 1, t, m, 0) - floor_sum(n + 1, d, 1, 0)); } std::cout << n << '\n'; } }