Q = int(input()) for q in range(Q): A,B,C = map(int,input().split()) if C==1: print(-1) continue if A < C: print(B) continue bit = [] while A>0: bit.append(A%C) A //= C bit.reverse() M = len(bit) sum = 0 if bit[1]==0 or bit[0]*C+bit[1]<=2*C-2: sum += 2 else : sum += 3 for i in range(2,M): if(bit[i]>0) : sum += 1 sum += M-2 print(sum*B)