#include #define rep(i,a,b) for(int i=a;i=b;i--) #define fore(i,a) for(auto &i:a) #pragma GCC optimize ("-O3") using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); } //--------------------------------------------------------------------------------------------------- int mod = 1000000007; int add(int x, int y) { return (x += y) >= mod ? x - mod : x; } template int add(int x, T... y) { return add(x, add(y...)); } int mul(int x, int y) { return 1LL * x * y % mod; } template int mul(int x, T... y) { return mul(x, mul(y...)); } int sub(int x, int y) { return add(x, mod - y); } int modpow(int a, long long b) { int ret = 1; while (b > 0) { if (b & 1) ret = 1LL * ret * a % mod; a = 1LL * a * a % mod; b >>= 1; } return ret; } int modinv(int a) { return modpow(a, mod - 2); } int legendre(int a, int p) { mod = p;int ret=modpow(a,(p-1)/2);if(ret==p-1)ret=-1;return ret;} pair mul(pair &u, pair &v, int w) { return {add(mul(u.first,v.first), mul(u.second,v.second,w)),add(mul(u.first,v.second),mul(u.second, v.first)) };}; int modsqrt(int a, int p) { mod = p;if (a == 0) return 0; if (p == 2) return a; if (modpow(a, (p - 1) / 2) != 1) return -1; int b=2;while(modpow((1LL*b*b-a+p)%p, (p - 1) / 2) == 1) b++;int w = (1LL * b * b - a + p) % p; int e = (p + 1) / 2;auto ret = make_pair(1, 0);auto v = make_pair(b, 1); while (e > 0) {if (e & 1) ret = mul(ret, v, w);v = mul(v, v, w);e /= 2;}return ret.first;} // ret == 0なら解1つ、!=0ならP-retも答え /*---------------------------------------------------------------------------------------------------             ∧_∧       ∧_∧  (´<_` )  Welcome to My Coding Space!      ( ´_ゝ`) /  ⌒i     /   \    | |     /   / ̄ ̄ ̄ ̄/  |   __(__ニつ/  _/ .| .|____      \/____/ (u ⊃ ---------------------------------------------------------------------------------------------------*/ int P, R, Q, A, B, C; //--------------------------------------------------------------------------------------------------- int f() { return mul(sub(mul(B, B, modinv(mul(4, A))), C),modinv(A)); } int rev(int x) { return sub(x, mul(B, modinv(mul(2, A)))); } //--------------------------------------------------------------------------------------------------- void _main() { cin >> P >> R >> Q; mod = P; rep(_, 0, Q) { cin >> A >> B >> C; int b = f(); if (legendre(b, P) < 0) { printf("-1\n"); continue; } int a = modsqrt(b, P); if (a == 0) printf("%d\n", rev(0)); else { int aa = P - a; a = rev(a), aa = rev(aa); if (a > aa) swap(a, aa); printf("%d %d\n", a, aa); } } }