P,R=map(int,input().split()) from collections import defaultdict Q=int(input()) def modinv(X): return pow(X,P-2,P) revR=modinv(R) Right= defaultdict(int) for i in range(100): Right[i] = pow(revR,i,P) Left =defaultdict(int) R100=pow(R,200,P) for i in range(5*10**6): Left[pow(R100,i,P)] = i def solve(a,b,c): T=(b**2-4*a*c)*modinv(4*a*a)%P S=b*modinv(2*a)%P # (X+S)**2 == T なるXを一つ見つける # R**u == T のuを見つける if T == 0: print((-S) %P) return order = -1 for j in range(200): key= Right[j]*T%P if key in Left.keys(): order = 200* Left[key] + j break order =order % P if order%2!=0: print(-1) return else: V= pow(R,order//2,P) mini,maxi=min((V-S)%P,(-V-S)%P),max((V-S)%P,(-V-S)%P) print(mini,maxi) return for i in range(Q): a,b,c=map(int,input().split()) solve(a,b,c)