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