# -*- coding: utf-8 -*- from __future__ import annotations from dataclasses import dataclass @dataclass(frozen=True) class MwfData: """ Purpose: Represents a data structure for computing weighted maximum prefix sums. Fields: sum : total accumulated sum best : maximum prefix value dx : length / shift amount (used to compute arg) arg : argmax (smallest arg if tie) """ sum: int best: int = 0 dx: int = 0 arg: int = 0 def __mul__(self, other: "MwfData") -> "MwfData": assert self.dx >= 0 and self.arg >= 0 and other.dx >= 0 and other.arg >= 0 ssum = self.sum + other.sum if other.dx == 0: return MwfData(ssum, self.best, self.dx, self.arg) cand_r = self.sum + other.best if self.dx == 0: return MwfData(ssum, cand_r, other.dx, other.arg) sdx = self.dx + other.dx cand_l = self.best if cand_l >= cand_r: return MwfData(ssum, cand_l, sdx, self.arg) return MwfData(ssum, cand_r, sdx, self.dx + other.arg) def __pow__(self, k: int) -> "MwfData": assert self.dx >= 0 and self.arg >= 0 and k >= 0 ssum = self.sum * k if k == 0 or self.dx == 0: return MwfData(ssum) sdx = self.dx * k if self.sum > 0: sbest = (k - 1) * self.sum + self.best sarg = (k - 1) * self.dx + self.arg return MwfData(ssum, sbest, sdx, sarg) return MwfData(ssum, self.best, sdx, self.arg) def floor_prod(n: int, m: int, a: int, b: int, e: MwfData, x: MwfData, y: MwfData): """ Requires: - integers n,m,a,b with 0<=n, 0=0 """ assert 0 <= n and 0 < m and 0 <= a and 0 <= b c = (a * n + b) // m pre, suf = e, e while True: p, a = divmod(a, m) x *= (y ** p) q, b = divmod(b, m) pre *= (y ** q) c -= (p * n + q) if c == 0: return pre * (x ** n) * suf d = (m * c - b - 1) // a + 1 suf = y * (x ** (n - d)) * suf n, m, a, b, c, x, y = c - 1, a, m, m - b - 1 + a, d, y, x def argmax_weighted_floor(n: int, m: int, a: int, b: int, c: int, d: int) -> tuple[int, int]: """ argmwf(n,m,a,b,c,d) = ( max_{0<=i 0 and m > 0 res: MwfData = floor_prod( n, m, c, d, MwfData(0), MwfData(a, 0, 1, 0), MwfData(b), ) assert res.best is not None and res.arg is not None return res.best, res.arg if __name__ == '__main__': import sys T = int(sys.stdin.readline()) for _ in range(T): N, M, A, B, C, D = map(int, sys.stdin.readline().split()) max_val, _argmax = argmax_weighted_floor(N, M, A, B, C, D) print(max_val)