#include #include #include int64_t modpow(int64_t a, int64_t b, int64_t m) { int64_t ret = 1; for (; b > 0; b >>= 1) { if (b & 1) ret = ret * a % m; a = a * a % m; } return ret; } int64_t modinv(int64_t a, int64_t p) { return modpow(a, p - 2, p); } int main() { int64_t p, r; std::cin >> p >> r; auto modulo = [&](int64_t a) { a %= p; if (a < 0) a += p; return a; }; constexpr int S = 5000000; constexpr int T = (1000000000 + S - 1) / S; int64_t rs = 1; std::vector> baby; for (int i = 0; i < S; i++) { baby.emplace_back(rs, i); rs = rs * r % p; } rs = modinv(rs, p); std::sort(baby.begin(), baby.end()); auto modlog = [&](int64_t a) -> int64_t { if (a == 0) return 1000000000; int64_t giant = 1; for (int i = 0; i < T; i++) { auto it = std::lower_bound(baby.begin(), baby.end(), std::make_pair(a * giant % p, 0)); if (it != baby.end() && a * giant % p == it->first) { return it->second + i * S; } giant = giant * rs % p; } return -1; }; int q; std::cin >> q; while (q--) { int64_t a, b, c; scanf("%lld %lld %lld", &a, &b, &c); int64_t d = modulo(b * b - 4 * a * c); int64_t e = modlog(d); if (e == -1 || e % 2 == 1) { puts("-1"); } else { d = e == 1000000000 ? 0LL : modpow(r, e / 2, p); int64_t x1 = modulo((-b + d) * modinv(2 * a % p, p)); int64_t x2 = modulo((-b - d) * modinv(2 * a % p, p)); if (x1 > x2) std::swap(x1, x2); if (x1 == x2) { printf("%lld\n", x1); } else { printf("%lld %lld\n", x1, x2); } } } }