import sys readline = sys.stdin.buffer.readline # calc sum_{i=0}^{n-1} floor((ai + b) / m) def floor_sum_unsigned(n: int, m: int, a: int, b: int) -> int: assert n >= 0 and m > 0 and a >= 0 and b >= 0 ans = 0 while True: if a >= m: ans += (n * (n - 1) >> 1) * (a // m) a %= m if b >= m: ans += n * (b // m) b %= m y_max = a * n + b if y_max < m: return ans n, b, m, a = y_max // m, y_max % m, a, m def solve(n: int, d: int, m: int, s: int) -> int: assert n >= 0 and d > 0 and m >= 0 and s >= 0 pow2s, dm = 1 << s, d * m if pow2s != dm: n = min(n, d * pow2s // abs(dm - pow2s)) n -= abs(floor_sum_unsigned(n + 1, pow2s, m, 0) - floor_sum_unsigned(n + 1, d, 1, 0)) return n for _ in range(int(readline())): n, d, m, s = map(int, readline().split()) print(solve(n, d, m, s))