def gcd(a, b): while b: a, b = b, a % b return a def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): m = 1 << n.bit_length() // 8 for c in range(1, 99): def f(x): return (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def prime_factors(n, return_e: bool = False): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return list(ret.keys()) # def prime_factors(n, return_e: bool = True): # """ # nの素因数分解を指数付きで返す 計算量O(√N) O(n^(1/4))もある # https://qiita.com/drken/items/a14e9af0ca2d857dad23#4-%E7%B4%A0%E5%9B%A0%E6%95%B0%E5%88%86%E8%A7%A3 # """ # assert 1 <= n # pfs = [] # a = 2 # while a**2 <= n: # if n % a == 0: # ex = 0 # while n % a == 0: # ex += 1 # n //= a # pfs.append((a, ex) if return_e else a) # a += 1 # if n != 1: # pfs.append((n, 1) if return_e else n) # return pfs def primitive_root(p: int) -> int: """素数pに対する何らかの原始根rを一つ求める (rの位数はp-1) https://manabitimes.jp/math/842 https://37zigen.com/primitive-root/ 最速ではない """ if p == 2: return 1 from random import randint p_1_pfs = prime_factors(p-1, return_e=False) cnt=0 while cnt tuple: """ 返り値は(gcd(a,b),x) (ただしxa≡g (mod b) 0<=x=0) m0 += b // s return (s, m0) def eea(a: int, b: int) -> tuple: """ ax+by=gcd(a,b)なる(x,y)を求める(拡張されたユークリッドの互除法) (extended_euclidean_algorithm)(元のユークリッドの互除法はgcdを求める手法を指す) https://qiita.com/drken/items/b97ff231e43bce50199a https://ja.wikipedia.org/wiki/ユークリッドの互除法 <-英語版が優秀すぎ https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm また、以上の話題は連分数展開とも関連があるらしい """ g, x = _inv_gcd(a, abs(b)) y = (b//abs(b))*(g-a*x)//abs(b) # assert (g-a*x) % abs(b) == 0 return (x, y) def main(): import sys from math import gcd input = sys.stdin.buffer.readline T = int(input()) for _ in range(T): p, k, a = map(int, input().split()) g = primitive_root(p) y = discrete_logarithm(g, a, p) gkp = gcd(k, p-1) if y % gkp != 0: print(-1) continue z = (y//gkp)*eea(k//gkp, -(p-1)//gkp)[0] x = pow(g, z % (p-1), p) print(x) if __name__ == '__main__': main()