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