#include <iostream>
using i64 = long long;

i64 f(const i64 n, const i64 m, i64 a, i64 b) {
    i64 ret = a / m * n * (n - 1) / 2 + b / m * n;
    a %= m;
    b %= m;

    const i64 p = (a * n + b) / m, q = p * m - b;
    if (p > 0) {
        ret += (n - (q + a - 1) / a) * p + f(p, a, m, (a - q % a) % a);
    }
    return ret;
}

int main() {
    int t;
    std::cin >> t;
    while (t--) {
        int n, m, a, b;
        std::cin >> n >> m >> a >> b;
        std::cout << f(n, m, a, b) << '\n';
    }

    return 0;
}
