import math q = int(input()) for _ in range(q): a, b, c = map(int, input().split()) if c == 1: print(-1) continue num = [] while True: a, mod = divmod(a, c) num.append(mod) if a == 0: break # print(num) if len(num) == 1: print(b) continue ans = b * len(num) - b for i in range(len(num)): if num[i] != 0: ans += b if num[-1] == 1 and 0 < num[-2] < c-1: ans -= b # print(num) print(ans)