#include "bits/stdc++.h" using namespace std; #ifdef _DEBUG #include "dump.hpp" #else #define dump(...) #endif #define int long long #define rep(i,a,b) for(int i=(a);i<(b);i++) #define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--) #define all(c) begin(c),end(c) const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f; const int MOD = (int)(1e9) + 7; template bool chmax(T &a, const T &b) { if (a < b) { a = b; return true; } return false; } template bool chmin(T &a, const T &b) { if (b < a) { a = b; return true; } return false; } // 累乗 // O(log e) // mod^2 が long long の最大値より大きければオーバーフローするので掛け算に modmul を使う long long modpow(long long a, long long e, long long mod) { long long res = 1; while (e > 0) { if (e & 1)res = res * a % mod; // modmul(res, a, mod); a = a * a % mod; // modmul(a, a, mod); e >>= 1; } return res; } // 逆元 // O(log mod) long long modinv(long long a, long long mod) { return modpow(a, mod - 2, mod); } // Legendre symbol // a|p なら 0 // a が平方剰余なら 1 // a が平方非剰余なら -1 int legendre(long long a, long long p) { long long l = modpow(a, (p - 1) / 2, p); return l == p - 1 ? -1 : l; } long long modsqrt(long long a, long long p) { int l = legendre(a, p); if (l != 1)return l; long long S = 0, Q = p - 1; while (!(Q & 1)) { S++; Q >>= 1; } long long z = 1; while (legendre(z, p) == 1)z++; long long M = S; long long c = modpow(z, Q, p); long long t = modpow(a, Q, p); long long R = modpow(a, (Q + 1) / 2, p); while (t != 1) { for (int i = 1; i < M; i++) { if (modpow(t, 1 << i, p) != 1)continue; long long b = modpow(c, 1 << (M - i - 1), p); c = b * b % p; t = t * b % p * b % p; R = R * b % p; break; } } return R; } signed main() { cin.tie(0); ios::sync_with_stdio(false); int P = 17; rep(a, 0, P) { legendre(a, P); } int p, r, q; cin >> p >> r >> q; rep(_, 0, q) { int a, b, c; cin >> a >> b >> c; int ainv = modinv(a, p); int A = ((b*b%p*modinv(4, p) % p*ainv%p*ainv%p + p - c) % p)*ainv%p; int X = modsqrt(A, p); if (X <= 0) { cout << X << endl; } else { int Y = p - X; int x = (X + p - b * modinv(2, p) % p * ainv) % p; int y = (Y + p - b * modinv(2, p) % p * ainv) % p; if (x > y)swap(x, y); cout << x << " " << y << endl; } } return 0; }