#include // min #include // countl_zero #include // uint64_t #include // cin, cout, ios #include // swap using u64 = uint64_t; using u128 = unsigned __int128; // calc sum_{i=0}^{n-1} floor((ai + b) / m) (mod 2^64) u64 floor_sum_unsigned(u128 n, u128 m, u128 a, u128 b) { u64 ans = 0; for(;;) { if (a >= m) { ans += (u64)((n * (n - 1) >> 1) * (a / m)); a %= m; } if (b >= m) { ans += (u64)(n * (b / m)); b %= m; } u128 ymax = a * n + b; if (ymax < m) { return ans; } n = ymax / m; b = ymax % m; std::swap(a, m); } } // calc min(floor(a * 2^s / b), 2^64 - 1) u64 div_helper(u128 a, u128 b, int s) { u64 ans = 0; for(;;) { int t = std::min(s, std::countl_zero((u64)(a >> 64))); a <<= t; if (ans > 0) { if (std::countl_zero(ans) < t) { return ~(u64)0; } ans <<= t; } s -= t; ans = (u64)(std::min((u128)ans + a / b, (u128)(~(u64)0))); a %= b; if (s == 0) { return ans; } } } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); int q; std::cin >> q; for (int i = 0; i < q; i++) { u64 n, d, m; int s; std::cin >> n >> d >> m >> s; u128 pow2s = (u128)1 << s, dm = (u128)d * (u128)m; if (pow2s < dm) { n = std::min(n, div_helper((u128)d, dm - pow2s, s)); n -= floor_sum_unsigned(n + 1, pow2s, m, 0) - floor_sum_unsigned(n + 1, d, 1, 0); } else if (pow2s > dm) { n = std::min(n, div_helper((u128)d, pow2s - dm, s)); n -= floor_sum_unsigned(n + 1, d, 1, 0) - floor_sum_unsigned(n + 1, pow2s, m, 0); } std::cout << n << '\n'; } return 0; }