class ModP: def __init__(self,p,r): self.p = p self.r = r self.log = {} self.exp = {} self.log[0] = -1 self.exp[-1] = 0 x = 1 for i in range(p-1): self.log[x] = i self.exp[i] = x x = (x*r)%p def multi(self,a,b): if a==-1 or b==-1: return -1 else: return (a+b)%(self.p-1) def rec(self,a): return (-a)%(self.p-1) def plus(self,a,b): if a==-1: return b elif b==-1: return a else: return self.log[(self.exp[a]+self.exp[b])%self.p] def opp(self,a): if a==-1: return -1 else: return self.log[self.p-self.exp[a]] def sqrt(self,a): if a==-1: return -1 elif a%2==1: return -2 else: return a/2 def solve(self,a,b,c): a,b,c = self.log[a],self.log[b],self.log[c] y = self.sqrt(self.plus(self.multi(b,b),self.opp(self.multi(self.log[4%self.p],self.multi(a,c))))) if y==-2: return -1 elif y==-1: return self.exp[self.multi(self.opp(b),self.rec(self.multi(self.log[2],a)))] else: x = self.exp[self.multi(self.plus(self.opp(b),y),self.rec(self.multi(self.log[2],a)))] y = self.exp[self.multi(self.opp(self.plus(b,y)),self.rec(self.multi(self.log[2],a)))] if x>y: x,y = y,x return "%d %d"%(x,y) def main(): P,R = list(map(int,input().split())) pclass = ModP(P,R) Q = int(input()) for i in range(Q): a,b,c = list(map(int,input().split())) print(pclass.solve(a,b,c)) if __name__ == '__main__': main()