M = 10 ** 6 + 100 primes = [] lpf = [-1] * M phi = [0] * M phi[1] = 1 for i in range(2, M): p = lpf[i] if p == -1: primes.append(i) p = lpf[i] = i phi[i] = i - 1 for q in primes: j = i * q if j >= M: break lpf[j] = q if q == p: phi[j] = phi[i] * p break phi[j] = phi[i] * (q - 1) from math import gcd def solve(b, n, m): if gcd(m, b) != 1: return -1 tmp = phi[b] t = phi[b] while tmp != 1: p = lpf[tmp] e = 0 while tmp % p == 0: tmp //= p e += 1 lb, ub = 0, e + 1 while ub - lb > 1: mid = (ub + lb) // 2 if pow(m, t // p ** mid, b) == 1: lb = mid else: ub = mid t //= p ** lb assert pow(m, t, b) == 1 c = 0 g = b while t != 1: g = gcd(g, t) if g == 1: return -1 t //= g c += 1 c = max(c + 1, n) bcn = b ** (c + n) mbc = m for _ in range(c): mbc = pow(mbc, b, bcn) q, r = divmod(mbc, b ** c) if r != 1: return -1 return q for _ in range(int(input())): b, n, m = map(int, input().split()) print(solve(b, n, m))