#include // assert #include // cin, cout, ios #include // swap, pair using ll = long long; template bool chmax(T& a, T b){if(a < b){a = b; return true;} return false;} template constexpr std::pair divmod(T a, T b) { T q = a / b; T r = a % b; return {q, r}; } // 商を無限大方向に切り下げる除算(剰余が0でない時の符号は除数の符号に一致) template constexpr std::pair divmod_floor(T a, T b) { // 標準の truncating 除算を使う T q = a / b; T r = a % b; // もし符号が食い違っていたら 1 調整 if ((r != 0) && ((r > 0) != (b > 0))) { q -= 1; r += b; } return {q, r}; } // 剰余が非負になる除算(ユークリッド除算) template constexpr std::pair divmod_euclid(T a, T b) { // 標準の truncating 除算を使う T q = a / b; T r = a % b; // 剰余が負なら 1 調整 if (r < 0) { if (b > 0) { q -= 1; r += b; } else { q += 1; r -= b; } } return {q, r}; } // max_{f(x) in [L, R)} // f(x) = (ax + b * floor((cx + d) / m)) template T mwf_naive(T l, T r, T m, T a, T b, T c, T d) { assert(l < r && 0 < m); T res = a * l + b * divmod_floor(c * l + d, m).first; for (T x = l; x < r; x++) { T val = a * x + b * divmod_floor(c * x + d, m).first; chmax(res, val); } return res; } int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); int t; ll n, m, a, b, c, d, ans; std::cin >> t; for(int i = 0; i < t; i++) { std::cin >> n >> m >> a >> b >> c >> d; assert(n > 0 && m > 0); ans = mwf_naive(0, n, m, a, b, c, d); std::cout << ans << '\n'; } }