use std::io::Write; fn run() { input! { t: usize, ask: [(u64, u64, u64); t], } let out = std::io::stdout(); let mut out = std::io::BufWriter::new(out.lock()); for (mut p, mut q, k) in ask { let g = gcd(p, q); p /= g; q /= g; if p > q { std::mem::swap(&mut p, &mut q); } if p == 1 { writeln!(out, "{}", k * g).ok(); continue; } let n = (p - 1) * (q - 1) - 1; let u = n / q; let cnt = u + floor_sum(u + 1, p, q, n - q * u); if cnt < k { writeln!(out, "{}", g * ((p - 1) * (q - 1) + k - cnt - 1)).ok(); continue; } let mut ok = n; let mut ng = 0; while ok - ng > 1 { let mid = (ok + ng) / 2; let u = mid / q; let cnt = u + floor_sum(u + 1, p, q, mid - q * u); if cnt >= k { ok = mid; } else { ng = mid; } } writeln!(out, "{}", ok).ok(); } } fn gcd(a: u64, b: u64) -> u64 { if b == 0 { a } else { gcd(b, a % b) } } fn main() { run(); } // ---------- begin input macro ---------- // reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 #[macro_export] macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } #[macro_export] macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } #[macro_export] macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // ---------- end input macro ---------- // ---------- begin floor sum ---------- // sum_{i = 0}^{n - 1} floor((ai + b) / m) pub fn floor_sum(n: u64, m: u64, mut a: u64, mut b: u64) -> u64 { assert!(n <= 10u64.pow(9)); assert!(1 <= m && m <= 10u64.pow(9)); let mut ans = 0; ans += a / m * n * (n - 1) / 2 + b / m * n; a %= m; b %= m; let p = a * n + b; if p >= m { ans += floor_sum(p / m, a, m, p % m); } ans } // ---------- end floor sum ----------