def floorSum(n, m, a, b): if n == 0: return 0 ans = n * (n - 1) * (a // m) // 2 + n * (b // m) a %= m b %= m last = a * (n - 1) + b last_div = last // m last_mod = last % m ans += last_div + floorSum(last_div, a, m, last_mod) return ans def solve(): N, D, M, S = map(int, input().split()) if M * D == 2 ** S: return N if M * D > 2 ** S: lim = (M * (D - 1) - 1) // (M * D - 2 ** S) print(lim > N) return floorSum(lim, M, 2 ** S - M * D, 2 ** S) if M * D < 2 ** S: lim = (2 ** S - 1) // (2 ** S - M * D) print(lim > N) return floorSum(lim, M, M * D - 2 ** S, M * (D - 1) - 1) Q = int(input()) for i in range(Q): print(solve())