## https://yukicoder.me/problems/no/915 from collections import deque def main(): Q = int(input()) abc = [] for _ in range(Q): a, b, c = map(int, input().split()) abc.append((a, b ,c)) for a, b, c in abc: if c == 1: print(a * b) continue queue = deque() b_map = {a: 0} queue.append(a) while len(queue) > 0: x = queue.popleft() if x == 0: break if x % c == 0: d = x // c if d not in b_map: b_map[d] = b_map[x] + 1 queue.append(d) if x - (c - 1) >= 0: e = x - (c - 1) if e not in b_map: b_map[e] = b_map[x] + 1 queue.append(e) else: if 0 not in b_map: b_map[0] = b_map[x] + 1 queue.append(0) else: d = x - (x % c) if d not in b_map: b_map[d] = b_map[x] + 1 queue.append(d) if x - (c - 1) >= 0: e = x - (c - 1) if e not in b_map: b_map[e] = b_map[x] + 1 queue.append(e) else: if 0 not in b_map: b_map[0] = b_map[x] + 1 queue.append(0) print(b_map[0] * b) if __name__ == "__main__": main()