#include // min #include // countl_zero #include // uint64_t #include // cin, cout, ios #include // swap using u64 = uint64_t; using u128 = unsigned __int128; u64 floor_sum_unsigned(u128 n, u128 m, u128 a, u128 b) { u64 x = 0; while(n > 0) { x += (u64)(a / m * (n * (n - 1) >> 1) + b / m * n); a %= m; b = a * n + b % m; n = b / m; b %= m; std::swap(a, m); } return x; } 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) { ans = std::countl_zero(ans) >= t ? ans << t : -1ULL; } s -= t; ans = (u64)(std::min((u128)ans + a / b, (u128)(-1ULL))); 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 t = (u128)1 << s, u = (u128)d * (u128)m; if(t < u) { n = std::min(n, div_helper(d, u - t, s)); n -= floor_sum_unsigned(n + 1, t, m, 0) - floor_sum_unsigned(n + 1, d, 1, 0); } else if(t > u) { n = std::min(n, div_helper(d, t - u, s)); n -= floor_sum_unsigned(n + 1, d, 1, 0) - floor_sum_unsigned(n + 1, t, m, 0); } std::cout << n << '\n'; } return 0; }