#![allow(unused_imports)] #![allow(non_snake_case)] use std::cmp::*; use std::collections::*; use std::io::Write; #[allow(unused_macros)] macro_rules! debug { ($($e:expr),*) => { #[cfg(debug_assertions)] $({ let (e, mut err) = (stringify!($e), std::io::stderr()); writeln!(err, "{} = {:?}", e, $e).unwrap() })* }; } fn main() { let q = read::(); for i in 0..q { let v = read_vec::(); let (a, b, c) = (v[0], v[1], v[2]); if c == 1 { println!("{}", a * b); continue; } let mut ans = 0; let mut cur_multiplied = 1; let mut loop_cnt = 0; while cur_multiplied * c < a { cur_multiplied *= c; loop_cnt += 1; } ans += loop_cnt; let mut a = a; while a != 0 { a -= a / cur_multiplied * cur_multiplied; ans += 1; while cur_multiplied > a { cur_multiplied /= c; } } println!("{}", ans * b); } } fn read() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec() -> Vec { read::() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() }