# calc sum_{i=0}^{n-1} floor((ai + b) / m) def floor_sum(n, m, a, b) x = 0 while n > 0 if a < m && a >= 0 q, a = a.divmod(m) x += n * (n - 1) / 2 * q end if b < m && b >= 0 q, b = b.divmod(m) x += n * q end n, b = (a * n + b).divmod(m) m, a = a, m end x end def solve(n, d, m, s) pow2s, dm = 1 << s, d * m if pow2s != dm n = [n, d * pow2s / (pow2s - dm).abs].min n -= (floor_sum(n + 1, pow2s, m, 0) - floor_sum(n + 1, d, 1, 0)).abs end return n end for _ in 1..gets.to_i n, d, m, s = gets.split.map &:to_i puts solve(n, d, m, s) end