import sys readline = sys.stdin.readline Q = int(readline()) Ans = [None]*Q for qu in range(Q): a, b, c = map(int, readline().split()) if c == 1: Ans[qu] = -1 continue cnt = 0 twosteps = set(range(c+1, 2*c-1)) while a > 0: if a in twosteps: cnt += 2 a = 0 continue elif a % c: a -= a%c else: a //= c cnt += 1 Ans[qu] = b*cnt print('\n'.join(map(str, Ans)))