from heapq import * def solve(): x, y, a = map(int, input().split()) E = [] X = [x, y] s = x t = y while x > 0: nx = x // a X.append(nx) E.append((x, nx, 1)) x = nx while y > 0: ny = y // a E.append((ny, ny * a, 1)) E.append((ny + 1, (ny + 1) * a, 1)) E.append((ny, ny + 1, 1)) E.append((ny + 1, ny, 1)) X.append(ny) X.append(ny * a) X.append(ny + 1) X.append((ny + 1) * a) y = ny X_ = sorted(list(set(X))) X = {x: i for i, x in enumerate(X_)} le = len(X) edges = [[] for _ in range(le)] for u, v, c in E: edges[X[u]].append((X[v], c)) for i in range(le - 1): d = X_[i + 1] - X_[i] edges[i].append((i + 1, d)) edges[i + 1].append((i, d)) dist = [1 << 60] * le s = X[s] t = X[t] dist[s] = 0 hq = [s] while hq: tmp = heappop(hq) d = tmp // le pos = tmp - le * d if dist[pos] < d: continue for npos, c in edges[pos]: nd = d + c if nd < dist[npos]: dist[npos] = nd heappush(hq, nd * le + npos) print(dist[t]) for _ in range(int(input())): solve()