# calc sum_{i=0}^{n-1} floor((ai + b) / m) def floor_sum_unsigned(n, m, a, b) ans = 0 while true if a >= m ans += (n * (n - 1) >> 1) * (a / m) a %= m end if b >= m ans += n * (b / m) b %= m end y_max = a * n + b if y_max < m return ans end n, b = y_max.divmod(m) m, a = a, m end end def solve(n, d, m, s) pow2s, dm = 1 << s, d * m if pow2s != dm n = [n, d * pow2s / (dm - pow2s).abs].min n -= (floor_sum_unsigned(n + 1, pow2s, m, 0) - floor_sum_unsigned(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