#include <algorithm> // min
#include <bit> // countl_zero
#include <cstdint> // uint64_t
#include <iostream> // cin, cout, ios
#include <utility> // 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 && (n | m | a | b) >> 64 > 0) {
        x += 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);
    }
    u64 nl = n, ml = m, al = a, bl = b;
    while(nl > 0 && (nl | ml | al | bl) >> 32 > 0) {
        x += al / ml * (u64)((u128)nl * ((u128)(nl - 1)) >> 1) + bl / ml * nl;
        al %= ml;
        b = (u128)al * (u128)nl + bl % ml;
        nl = b / ml;
        bl = b % ml;
        std::swap(al, ml);
    }
    while(nl > 0) {
        x += al / ml * (nl * (nl - 1) >> 1) + bl / ml * nl;
        al %= ml;
        bl = al * nl + bl % ml;
        nl = bl / ml;
        bl %= ml;
        std::swap(al, ml);
    }
    return x;
}

u64 div_helper(u128 a, u128 b, int s) {
    u64 x = 0;
    for(;;) {
        int t = std::min(s, std::countl_zero((u64)(a >> 64)));
        a <<= t;
        if(x > 0) {
            x = std::countl_zero(x) >= t ? x << t : -1ULL;
        }
        s -= t;
        x = (u64)(std::min((u128)x + a / b, (u128)(-1ULL)));
        a %= b;
        if(s == 0) {
            return x;
        }
    }
}

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;
}