#include using namespace std; long long int P, R, Q, A, B, C, D, x, y, it; static inline long long mdp(long long int a, long long int n){ long long int r = 1; while(n){ if(n & 1)r = r * a % P; a = a * a % P; n /= 2; } return r; } static inline long long pmdp(long long a, long long b){ long long int r = 1, s = 0, i1, i2, ro = a, n = (P + 1) / 2; swap(a, b); b = 1; //cout << " | " << a << " " << b << " (" << a << " + sqrt(" << ro << ")) "; while(n){ //cout << "(" << n << ", " << r << ", " << s << ", " << a << ", " << b << ") "; if(n & 1){ i1 = (a * r + (b * s % P) * ro) % P; i2 = (a * s + b * r) % P; r = i1; s = i2; } i1 = (a * a + (b * b % P) * ro) % P; i2 = (2 * a * b) % P; a = i1; b = i2; n /= 2; } //cout << r << " " << s << " | "; return r; } int main(){ scanf("%lld%lld%lld", &P, &R, &Q); it = mdp(2, P - 2); for(int Qi = 0; Qi < Q; ++Qi){ scanf("%lld%lld%lld", &A, &B, &C); B = B * mdp(A, P - 2) % P; C = C * mdp(A, P - 2) % P; A = 1; //cout << "X^2 + " << B << " X + " << C << " = 0 (mod " << P << ") "; D = (B * B + 4 * (P - 1) * C) % P; //cout << D << " "; if(mdp(D, (P - 1) / 2) == P - 1){puts("-1");continue;} if(D == 0){ x = 0; y = (((x + (P - 1) * B) % P) * it) % P; cout << y << endl; }else{ int i; for(i = 0; i < P; ++i)if(mdp((i * i + (P - 1) * D) % P, (P - 1) / 2) == P - 1){y = (i * i + (P - 1) * D) % P;break;} x = pmdp(y, i); //cout << x << " "; y = (((x + (P - 1) * B) % P) * it) % P; x = (((P - 1) * (x + B) % P) * it) % P; cout << min(x, y) << " " << max(x, y) << endl; } } return 0; }