MOD = 10 ** 9 + 7 INF = 10 ** 10 import sys sys.setrecursionlimit(100000000) dy = (-1,0,1,0) dx = (0,1,0,-1) from collections import deque from heapq import heapify,heappush,heappop def dfs(x,c): if x == 0: return 0 if 0 < x < c: return 1 if c <= x < 2 * c - 1: return 2 if x%c == 0: return dfs(x//c,c) + 1 else: return dfs(x - x%c,c) + 1 def main(): q = int(input()) for _ in range(q): a,b,c = map(int,input().split()) if c == 1: print(-1) continue ans = dfs(a,c) print(ans * b) if __name__ =='__main__': main()