INF = 10**2000 def solve(): n, m, a, b, c, d = map(int, input().split()) def eval(m, a, b, c, d, x: int) -> int: return a * x + b * ((c * x + d) // m) def f(n, m, a, b, c, d: int) -> int: if n <= 0: return -INF if c < 0 or d < 0: return f(n, m, a + b * (c // m), b, c % m, d % m) + b * (d // m) if a >= 0 and b >= 0: return eval(m, a, b, c, d, n-1) if a < 0 and b < 0: return eval(m, a, b, c, d, 0) if m == 1: return max(eval(m, a, b, c, d, 0), eval(m, a, b, c, d, n-1)) if c >= m: c1 = c // m c2 = c % m return f(n, m, a + b * c1, b, c2, d) if d >= m: d1 = d // m d2 = d % m return f(n, m, a, b, c, d2) + b * d1 k = (c * (n-1) + d) // m if a < 0: ans = f(k, c, b, a, m, m - d + c - 1) + b return max(ans, eval(m, a, b, c, d, 0)) ans = f(k, c, b, a, m, m - d - 1) return max(ans, eval(m, a, b, c, d, n-1)) ans = f(n, m, a, b, c, d) print(ans) t = int(input()) for _ in range(t): solve()