#include using namespace std; using uint = unsigned int; using lint = long long int; using ulint = unsigned long long int; template using V = vector; template using VV = V< V >; template void assign(V& v, int n, const U& a) { v.assign(n, a); } template void assign(V& v, int n, const Args&... args) { v.resize(n); for (auto&& e : v) assign(e, args...); } lint tmod(lint a, lint p) { assert(p > 0); return (a %= p) < 0 ? a + p : a; } int mod_pow(lint a, lint n, int p) { assert(n >= 0); a = tmod(a, p); lint res = 1; while (n > 0) { if (n & 1) { (res *= a) %= p; } (a *= a) %= p; n >>= 1; } return res; } lint mod_inv(lint a, lint p) { a = tmod(a, p); lint b = p, x = 1, u = 0; while (b) { lint q = a / b; swap(a -= q * b, b); swap(x -= q * u, u); } return a == 1 ? tmod(x, p) : -1; } int mod_log(lint g, lint x, int p) { g = tmod(g, p); x = tmod(x, p); int m = 5e5; static unordered_map mp; lint a = 1; if (mp.empty()) { for (int j = 0; j < m; ++j) { mp[a] = j; (a *= g) %= p; } } g = mod_inv(mod_pow(g, m, p), p), a = 1; for (int i = 0; i < (p - 1 + m - 1) / m; ++i) { if (mp.count(a * x % p)) { return i * m + mp[a * x % p]; } (a *= g) %= p; } return -1; } template Int ext_gcd(Int a, Int b, Int& x, Int& y) { Int u = y = 0, v = x = 1; while (b) { Int q = a / b; swap(a -= q * b, b); swap(x -= q * u, u); swap(y -= q * v, v); } return a; } int mod_root(lint a, lint n, int p, int g) { a = tmod(a, p); if (a == 0) { return n > 0 ? 0 : -1; } n = tmod(n, p - 1); int e = mod_log(g, a, p); assert(e != -1); lint x, y; int d = ext_gcd(n, p - 1, x, y); if (e % d) return -1; return mod_pow(g, e / d * x, p); } int main() { cin.tie(nullptr); ios_base::sync_with_stdio(false); int p, g, q; cin >> p >> g >> q; while (q--) { lint a, b, c; cin >> a >> b >> c; lint D = tmod(b * b - 4 * a * c, p); lint sqrt_D = mod_root(D, 2, p, g); if (sqrt_D == -1) { cout << -1 << '\n'; continue; } lint x = -b + sqrt_D; lint y = -b - sqrt_D; x = tmod(mod_inv(2 * a, p) * x, p); y = tmod(mod_inv(2 * a, p) * y, p); if (x > y) swap(x, y); cout << x; if (y != x) { cout << ' ' << y; } cout << '\n'; } }