#!/usr/bin/env node const divmod_euclid = (a, b) => { let [q, r] = [a / b, a % b]; if (r < 0n) { if (b > 0n) { q -= 1n; r += b; } else { q += 1n; r -= b; } } return [q, r]; } const mwf = (l, r, m, a, b, c, d) => { let n = r - l; let [qc0, rc0] = divmod_euclid(c, m); c = rc0; a += b * qc0; let [qd0, rd0] = divmod_euclid(d, m); d = rd0; let sum_acc = a * l + b * qd0; let max_acc = sum_acc; while (true) { n -= 1n; let y_max = (c * n + d) / m; if (max_acc < sum_acc) { max_acc = sum_acc; } let t = sum_acc + a * n + b * y_max; if (max_acc < t) { max_acc = t; } if ((a <= 0n && b <= 0n) || (a >= 0n && b >= 0n) || y_max == 0n) { return max_acc; } if (a < 0n) { sum_acc += a + b; } n = y_max; d = m - d - 1n; [m, c, a, b] = [c, m, b, a]; let qc = c / m; c %= m; a += b * qc; let qd = d / m; d %= m; sum_acc += b * qd; } } let [t, ...inputs] = require("fs") .readFileSync("/dev/stdin", "utf8") .trim() .split(/\s+/); t = Number(t); for (let i = 0; i < t; i += 1) { let [n, m, a, b, c, d] = inputs.slice(i * 6, i * 6 + 6).map((s) => BigInt(s)); console.log(mwf(0n, n, m, a, b, c, d).toString()); }