#include #include #include #include #include int modpow(int a, int b, int m) { int ret = 1; while (b > 0) { if (b & 1) ret = 1LL * ret * a % m; a = 1LL * a * a % m; b /= 2; } return ret; } int modinv(int a, int m) { return modpow(a, m - 2, m); } bool issquare(int a, int p) { return modpow(a, (p - 1) / 2, p) == 1; } int modsqrt(int a, int p) { if (a == 0) return 0; if (p == 2) return a; if (!issquare(a, p)) return -1; int b = 2; while (issquare((1LL * b * b - a + p) % p, p)) b++; int w = (1LL * b * b - a + p) % p; auto mul = [&](std::pair u, std::pair v) { int a = (1LL * u.first * v.first + 1LL * u.second * v.second % p * w) % p; int b = (1LL * u.first * v.second + 1LL * u.second * v.first) % p; return std::make_pair(a, b); }; // (b + sqrt(b^2-a))^(p+1)/2 int e = (p + 1) / 2; auto ret = std::make_pair(1, 0); auto v = std::make_pair(b, 1); while (e > 0) { if (e & 1) ret = mul(ret, v); v = mul(v, v); e /= 2; } return ret.first; } int main() { int p, r; std::cin >> p >> r; auto f = [&](long long x) { x %= p; if (x < 0) { x += p; } return x; }; int q; std::cin >> q; while (q--) { long long a, b, c; scanf("%lld %lld %lld", &a, &b, &c); long long d = f(b * b - 4 * a * c); if (d == 0) { long long x1 = f(f(-b) * modinv(f(2 * a), p)); printf("%lld\n", x1); } else if (!issquare(d, p)) { puts("-1"); continue; } else { d = modsqrt(d, p); long long x1 = f(f(-b + d) * modinv(f(2 * a), p)); long long x2 = f(f(-b - d) * modinv(f(2 * a), p)); if (x1 > x2) std::swap(x1, x2); printf("%lld %lld\n", x1, x2); } } }