#include #include #include #include #include #include #include #include #include #include #include #include #include #define getchar getchar_unlocked #define putchar putchar_unlocked #define _rep(_1, _2, _3, _4, name, ...) name #define rep2(i, n) rep3(i, 0, n) #define rep3(i, a, b) rep4(i, a, b, 1) #define rep4(i, a, b, c) for (int i = int(a); i < int(b); i += int(c)) #define rep(...) _rep(__VA_ARGS__, rep4, rep3, rep2, _)(__VA_ARGS__) using namespace std; using i64 = long long; using u8 = unsigned char; using u32 = unsigned; using u64 = unsigned long long; using f80 = long double; int get_int() { int c, n; while ((c = getchar()) < '0'); n = c - '0'; while ((c = getchar()) >= '0') n = n * 10 + (c - '0'); return n; } struct FastDiv { FastDiv() {} FastDiv(u64 n) : m(n) { s = (n == 1) ? 0 : 64 + __lg(n - 1); x = ((__uint128_t(1) << s) + n - 1) / n; } friend u64 operator / (u64 n, FastDiv d) { return __uint128_t(n) * d.x >> d.s; } friend u64 operator % (u64 n, FastDiv d) { return n - n / d * d.m; } u64 m, s, x; }; inline int pow_mod(int a, int e, FastDiv& mod) { int ret = 1; for (; e; e >>= 1, a = i64(a) * a % mod) if (e & 1) ret = i64(ret) * a % mod; return ret; } int msqrt(i64 a64, FastDiv& p, int z) { int a = a64 % p.m; if (a <= 1) return a; if (pow_mod(a, (p.m - 1) / 2, p) != 1) return -1; if ((p.m & 3) == 3) { return pow_mod(a, (p.m + 1) >> 2, p); } auto mul = [&] (int a, int b) { return i64(a) * b % p; }; if ((p.m & 7) == 5) { int v = pow_mod(2 * a, (p.m - 5) >> 3, p); int i = mul(mul(2 * a, v), v); return mul(mul(a, v), i - 1); } int q = p.m - 1, s = __builtin_ctz(q); q >>= s; int c = pow_mod(z, q, p); int x = pow_mod(a, (q - 1) >> 1, p); int r = mul(a, x), t = mul(r, x); while (t != 1) { int s2 = 1; for (int tmp = mul(t, t); tmp != 1; tmp = mul(tmp, tmp), ++s2); int b = c; rep(_, s - s2 - 1) b = mul(b, b); c = mul(b, b), r = mul(r, b), t = mul(t, c); s = s2; } return r; } void solve() { int PP, R; while (~scanf("%d %d", &PP, &R)) { int Q; scanf("%d", &Q); auto P = FastDiv(PP); int inv2 = pow_mod(2, P.m - 2, P); rep(_, Q) { int a = get_int(), b = get_int(), c = get_int(); int inv = pow_mod(a, P.m - 2, P); b = i64(b) * inv % P; c = i64(c) * inv % P; b = i64(b) * inv2 % P; int rhs = ((P.m - c) + i64(b) * b) % P; int r = msqrt(rhs, P, R); if (r < 0) { puts("-1"); } else { int ans1 = (i64(r) + P.m - b) % P; int ans2 = (i64(P.m) - r + P.m - b) % P; if (ans1 > ans2) swap(ans1, ans2); if (ans1 == ans2) { printf("%d\n", ans1); } else { printf("%d %d\n", ans1, ans2); } } } } } int main() { clock_t beg = clock(); solve(); clock_t end = clock(); fprintf(stderr, "%.3f sec\n", double(end - beg) / CLOCKS_PER_SEC); return 0; }