# calc sum_{i=0}^{n-1} floor((ai + b) / m) def floor_sum(n: int, m: int, a: int, b: int) -> int: assert n >= 0 and m > 0 x = 0 while n > 0: if a >= m or a < 0: q, a = divmod(a, m) x += (n * (n - 1) >> 1) * q if b >= m or b < 0: q, b = divmod(b, m) x += n * q n, b = divmod(a * n + b, m) m, a = a, m return x def solve(n: int, d: int, m: int, s: int) -> int: pow2s, dm = 2 ** s, d * m if pow2s != dm: n = min(n, (d * pow2s - 1) // abs(pow2s - dm)) n -= abs(floor_sum(n + 1, pow2s, m, 0) - floor_sum(n + 1, d, 1, 0)) return n for _ in range(int(input())): n, d, m, s = map(int, input().split()) print(solve(n, d, m, s))