fun main() { val builder = StringBuilder() val q = readInputLine().toInt() // 有志解説を読んでもよくわからない…… repeat(q) { val (a, b, c) = readInputLine().split(" ").map { it.toLong() } if (c == 1L) { builder.appendln(-1) } else { var tmp = a var cnt = 0L val ansCandidates = mutableSetOf() while (tmp != 0L) { if (tmp % c == 0L) { tmp /= c } else { ansCandidates.add(cnt + (tmp + c - 2L) / (c - 1L)) tmp = tmp / c * c } cnt++ } ansCandidates.add(cnt) builder.appendln(ansCandidates.minOrNull()!! * b) } } print(builder.toString()) } fun readInputLine(): String { return readLine()!! }