#include // cin, cout, ios #include // swap #include namespace mp = boost::multiprecision; mp::cpp_int floor_sum_unsigned(mp::cpp_int n, mp::cpp_int m, mp::cpp_int a, mp::cpp_int b) { mp::cpp_int ans = 0; for(;;) { if (a >= m) { ans += (n * (n - 1) >> 1) * (a / m); a %= m; } if (b >= m) { ans += n * (b / m); b %= m; } mp::cpp_int ymax = a * n + b; if (ymax < m) { return ans; } mp::divide_qr(ymax, m, n, b); std::swap(a, m); } } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); int q; std::cin >> q; for (int i = 0; i < q; i++) { mp::cpp_int n, d, m; int s; std::cin >> n >> d >> m >> s; mp::cpp_int pow2s = (mp::cpp_int)1 << s, dm = d * m; if (pow2s != dm) { n = mp::min(n, d * pow2s / mp::abs(dm - pow2s)); n -= mp::abs(floor_sum_unsigned(n + 1, pow2s, m, 0) - floor_sum_unsigned(n + 1, d, 1, 0)); } std::cout << n << '\n'; } return 0; }