#include #define FOR(i,a,b) for (int i=(a);i<(b);i++) #define FORR(i,a,b) for (int i=(a);i>=(b);i--) #define pb push_back using namespace std; typedef long long ll; typedef pair pii; typedef vector vi; typedef set si; const int inf = 1e9; const int mod = 1e9+7; ll p, q, r; map m; ll qu[3][10000]; vector > li; ll powMod(ll a, ll n, ll m){ ll p = 1; while(n > 0){ if(n & 1) p = p * a % m; a = a * a % m; n >>= 1; } return p; } main(){ cin.tie(0); ios::sync_with_stdio(false); cin >> p >> r >> q; ll inv2 = powMod(2, p - 2, p), invr = powMod(r, p - 2, p); FOR(i, 0, q){ ll a, b, c, d; cin >> a >> b >> c; d = powMod(a, p - 2, p); b = b * d % p * inv2 % p; c = c * d % p; d = b * b % p; c = (d - c + p) % p; qu[0][i] = b; qu[1][i] = c; qu[2][i] = -1; if(c != 0){ li.pb(pair(c, i)); } } ll a = 1, e = min(p-1, 10000000ll); FOR(i, 0, e){ m[a] = ll(i); a = a * r % p; } FOR(i, 0, 1+p/e){ FOR(j, 0, li.size()){ if(m.find(li[j].first) != m.end()){ qu[2][li[j].second] = i*e + m[li[j].first]; } li[j].first = li[j].first * a % p; } } FOR(i, 0, q){ if(qu[1][i] == 0){ cout << (p - qu[0][i])%p << endl; }else if(qu[2][i] % 2 != 0){ cout << -1 << endl; }else{ ll ans1, ans2; ans1 = (powMod(r, qu[2][i] / 2, p) - qu[0][i] + p)%p; ans2 = (powMod(r, qu[2][i] / 2 + (p-1) / 2, p) - qu[0][i] + p)%p; if(ans1 > ans2)swap(ans1, ans2); cout << ans1 << " " << ans2 << endl; } } }