import sys input = sys.stdin.buffer.readline from math import gcd f = [0 for i in range(50)] g = [0 for i in range(50)] h = [0 for i in range(50)] def q(n, m, a, b, c=0) -> None: if m == 0: f[c] = g[c] = h[c] = 0 return a1, a2 = a // m, a % m b1, b2 = b // m, b % m y = (a2 * n + b2) // m q(y, a2, m, m + a2 - b2 - 1, c + 1) nn = n * (n - 1) // 2 f[c] = n * y - f[c + 1] g[c] = n * y * y - f[c + 1] - 2 * h[c + 1] h[c] = nn * y + (f[c + 1] - g[c + 1]) // 2 g[c] += n * (2 * n - 1) * (n - 1) * a1 * a1 // 6 g[c] += 2 * nn * a1 * b1 g[c] += b1 * (b1) * n g[c] += 2 * a1 * h[c] g[c] += 2 * b1 * f[c] f[c] += a1 * nn + b1 * n h[c] += nn * (a1 * (2 * n - 1) + 3 * b1) // 3 return def main() -> None: n, m, a, b = map(int, input().split()) gccd = gcd(m, a) m, a, b = m // gccd, a // gccd, b // gccd ans = 0 q(n, m, a, b) ans -= (n - 1) * f[0] ans += 2 * h[0] t = a * (n - 1) // m y = m - a * (n - 1) + t * m q(n, m, a, y) ans += f[0] ans += h[0] ans -= n * (n + 1) // 2 * t k1, k2 = n // m, n % m ans -= (k1 + 1) * (k1 + 2) // 2 * k2 ans -= k1 * (k1 + 1) // 2 * (m - k2) print(ans) return for i in range(int(input())): main()