read_line.to_i.times do a, b, c = read_line.split.map(&.to_i64) if c == 1 puts -1 next end dfs = Hash(Int64, Int64).new do |h, n| if n == 0 h[n] = 0 elsif n % c == 0 h[n] = {h[n // c] + b, (n + c - 2)//(c - 1)*b}.min else h[n] = {h[n - n % c] + b, (n + c - 2)//(c - 1)*b}.min end end puts dfs[a] end