from typing import List, Tuple def solve(x: int, y: int, a: int) -> int: fromX: List[Tuple[int, int]] = [] c: int = 0 while 0 < x: fromX.append((x, c)) x //= a c += 1 fromX.append((x, c)) dp: List[Tuple[int, int, int]] = [(y, 0, 1e9)] while 1: [i, j, k] = dp[-1] d, r = i // a, i % a if r == 0: dp.append((d, min(j + 1, k + 2), k + a)) elif r == a - 1: dp.append((d, j + a, min(j + 2, k + 1))) else: dp.append((d, min(j + r + 1, k + (r + 1) + 1), min(j + (a - r) + 1, k + (a - (r + 1)) + 1))) if i == 0: break fromY = [] for i, j, k in dp: fromY.append((i + 1, k)) fromY.append((i, j)) def toX(n: int) -> int: return min(map(lambda b: abs(b[0] - n) + b[1], fromX)) ans = 1e9 if len(fromX) < 2: for i, j in fromX: ans = min(ans, *map(lambda p: abs(p[0] - i) + p[1] + j, fromY)) else: k = 2 for i, j in fromY: while i < fromX[k][0] and k + 1 < len(fromX): k += 1 ans = min(ans, abs(i - fromX[k - 2][0]) + j + fromX[k - 2][1], abs(i - fromX[k - 1][0]) + j + fromX[k - 1][1], abs(i - fromX[k][0]) + j + fromX[k][1]) return ans def main(): T = int(input()) for _ in range(T): print(solve(*map(int, input().split()))) if __name__ == '__main__': main()