import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(2*10**5+10) write = lambda x: sys.stdout.write(x+"\n") debug = lambda x: sys.stderr.write(x+"\n") writef = lambda x: print("{:.12f}".format(x)) ### 離散対数問題 def gcd2(a, b): """a*x + b*y = gcd(a,b)なるx,yも求める """ l = [] while b: l.append(divmod(a,b)) a, b = b, a%b x, y = 1, 0 for aa,bb in l[::-1]: x, y = y, x - aa*y return a, x, y def modinv(x, M): """素数ではないM、Mと互いに素なxに対し x * y == 1 mod M なるyを求める """ a,xx,yy = gcd2(x,M) return a,xx%M def dlog(x,y,M): """互いに素なx,Mに対してpow(x,i,M)==y なる最小のiを返す 存在しない場合Noneを返す """ l = int(M**0.5)+1 d = {} v = 1 for i in range(l+1): d[v] = i v *= x v %= M v = y _,tmp = modinv(pow(x,l,M), M) for i in range(l+1): if v in d: vv = 1 for j in range(l+1): if vv==v: break vv *= x v %= M return i*l + j v *= tmp v %= M return None def sub(a,b,c): ainv = pow(a, p-2, p) b = b * ainv % p c = c * ainv % p v = (b*b*inv4 - c)%p if v==0: return (-b*inv2)%p res = dlog(r,v,p) if res is None: return -1 elif res%2==1: return -1 kk1 = res//2 kk2 = (res+p-1)//2 bb = b * inv2 % p x1 = pow(r, kk1, p) - bb x2 = pow(r, kk2, p) - bb # print(res, v, r, kk1, kk2) return " ".join(sorted(map(str,(x1%p, x2%p)))) p,r = list(map(int, input().split())) q = int(input()) inv4 = pow(4, p-2, p) inv2 = pow(2, p-2, p) ans = [] for i in range(q): a,b,c = map(int, input().split()) ans.append(sub(a,b,c)) write("\n".join(map(str, ans)))