#include <bits/stdc++.h>

using i64 = long long;

i64 ceilDiv(i64 a, i64 b) {
    if (a >= 0) {
        return (a + b - 1) / b;
    } else {
        return a / b;
    }
}

i64 floorDiv(i64 a, i64 b) {
    if (a >= 0) {
        return a / b;
    } else {
        return (a - b + 1) / b;
    }
}
i64 exgcd(i64 a, i64 b, i64 &x, i64 &y) {
    if (!b) {
        x = 1;
        y = 0;
        return a;
    }
    i64 g = exgcd(b, a % b, y, x);
    y -= a / b * x;
    return g;
}

void solve() {
    i64 M, A, B, K;
    std::cin >> M >> A >> B >> K;
    
    if (K > A) {
        std::cout << "0\n";
        return;
    }
    
    if (K == A) {
        i64 ans = M / A - 1;
        ans -= M / B;
        ans += M / std::lcm(A, B);
        ans += M - M % B > M - M % A;
        std::cout << ans << "\n";
        return;
    }
    
    i64 x, y;
    i64 g = exgcd(A, B, x, y);
    if (K % g != 0) {
        std::cout << 0 << "\n";
        return;
    }
    
    A /= g, B /= g;
    K /= g;
    M /= g;
    
    x = 1LL * x * K % B;
    y = (K - A * x) / B;
    i64 L = A * B;
    
    i64 ans = 0;
    i64 l = std::max(ceilDiv(1 - A * x, L), ceilDiv(1 + B * y, L));
    i64 r = std::min(floorDiv(M - A * x, L), floorDiv(M + B * y, L));
    ans += std::max(0LL, r - l + 1);
    l = std::max(ceilDiv(1 + A * x, L), ceilDiv(1 - B * y, L));
    r = std::min(floorDiv(M + A * x, L), floorDiv(M - B * y, L));
    ans += std::max(0LL, r - l + 1);
    std::cout << ans << "\n";
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int T;
    std::cin >> T;
    
    while (T--) {
        solve();
    }
    
    return 0;
}