// calc sum_{i=0}^{n-1} floor((ai + b) / m) (mod 2^64) pub fn floor_sum_unsigned_mod64(n: u64, mut m: u128, a: u64, b: u64) -> u64 { let (mut ans, mut n, mut a, mut b) = (0u64, n as u128, a as u128, b as u128); loop { if a >= m { ans = ans.wrapping_add(((n * (n - 1) >> 1).wrapping_mul(a / m)) as u64); a %= m } if b >= m { ans = ans.wrapping_add((n.wrapping_mul(b / m)) as u64); b %= m } let y_max = a * n + b; if y_max < m { return ans; } (n, b, m, a) = (y_max / m, y_max % m, a, m) } } // calc min(floor(a * 2^s / b), 2^64 - 1) pub fn solve_div_helper(a: u64, b: u128, mut s: u32) -> u64 { assert!(b < (1u128 << 127)); if b == 0 { return !0u64; } let (mut ans, mut a) = (0u64, a as u128); loop { let t = s.min(a.leading_zeros()); a <<= t; if ans > 0 { if ans.leading_zeros() < t { return !0u64; } else { ans <<= t; } } s -= t; ans = match u64::try_from(a / b) { Ok(q) => ans.saturating_add(q), Err(_) => return !0u64, }; a %= b; if s == 0 { break ans; } } } pub fn solve(mut n: u64, d: u64, m: u64, s: u32) -> u64 { use std::cmp::Ordering::*; assert!(n < (1u64 << 60)); assert!(d < (1u64 << 60) && d > 0); assert!(m < (1u64 << 60)); assert!(s < 121); let (pow2s, dm) = (1u128 << s, (d as u128) * (m as u128)); n = n.min(solve_div_helper(d, dm.abs_diff(pow2s), s)); match pow2s.cmp(&dm) { Equal => n, Less => n .wrapping_sub(floor_sum_unsigned_mod64(n + 1, pow2s, m, 0)) .wrapping_add(floor_sum_unsigned_mod64(n + 1, d as u128, 1, 0)), Greater => n .wrapping_add(floor_sum_unsigned_mod64(n + 1, pow2s, m, 0)) .wrapping_sub(floor_sum_unsigned_mod64(n + 1, d as u128, 1, 0)), } } fn main() { use std::io::prelude::*; let stdin = std::io::stdin(); let stdout = std::io::stdout(); let stdinlock = stdin.lock(); let stdoutlock = stdout.lock(); let mut bufwriter = std::io::BufWriter::new(stdoutlock); let mut lines = stdinlock.lines(); let q = lines.next().unwrap().unwrap().parse::().unwrap(); for _ in 0..q { let l = lines.next().unwrap().unwrap(); let mut token = l.split_ascii_whitespace(); let n = token.next().unwrap().parse::().unwrap(); let d = token.next().unwrap().parse::().unwrap(); let m = token.next().unwrap().parse::().unwrap(); let s = token.next().unwrap().parse::().unwrap(); writeln!(&mut bufwriter, "{}", solve(n, d, m, s)).unwrap(); } }