using System; using System.Linq; using System.Collections.Generic; using System.IO; class MyClass { public static void Solve() { var Q = int.Parse(Console.ReadLine()); for (int _i = 0; _i < Q; _i++) { var input = Console.ReadLine().Split().Select(int.Parse).ToArray(); var A = input[0]; var B = input[1]; var C = input[2]; var queue = new Queue(); queue.Enqueue(new[] { A, 0 }); var ans = 0; while (A > 0) { if (A % C == 0) { A /= C; ans++; } else { A -= A % C; ans++; } } if (A != 0) { Console.WriteLine(-1); } else { Console.WriteLine((long)B * ans); } } } public static void Main() { var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false }; Console.SetOut(sw); Solve(); Console.Out.Flush(); } }