#pragma GCC optimization ("O3") #include using namespace std; using ll = long long; using vec = vector; using mat = vector; using pll = pair; #define INF (1LL<<61) #define MOD 1000000007LL //#define MOD 998244353LL #define EPS (1e-10) #define PR(x) cout << (x) << endl #define PS(x) cout << (x) << " " #define REP(i,m,n) for(ll (i)=(m),(i_len)=(n);(i)<(i_len);++(i)) #define FORE(i,v) for(auto (i):v) #define ALL(x) (x).begin(), (x).end() #define SZ(x) ((ll)(x).size()) #define REV(x) reverse(ALL((x))) #define ASC(x) sort(ALL((x))) #define DESC(x) {ASC((x)); REV((x));} #define BIT(s,i) (((s)>>(i))&1) #define pb push_back #define fi first #define se second template inline int chmin(T& a, T b) {if(a>b) {a=b; return 1;} return 0;} template inline int chmax(T& a, T b) {if(a=MOD) x-=MOD; return *this;} mint& operator-=(const mint& a) {if((x+=MOD-a.x)>=MOD) x-=MOD; return *this;} mint& operator*=(const mint& a) {(x*=a.x)%=MOD; return *this;} mint operator+(const mint& a) const {mint b(*this); return b+=a;} mint operator-(const mint& a) const {mint b(*this); return b-=a;} mint operator*(const mint& a) const {mint b(*this); return b*=a;} mint pow(ll t) const {if(!t) return 1; mint a=pow(t>>1); return (t&1?*this*a:a)*a;} mint inv() const {return pow(MOD-2);} mint& operator/=(const mint& a) {return *this*=a.inv();} mint operator/(const mint& a) const {mint b(*this); return b/=a;} }; istream &operator>>(istream& is, mint& a) {ll t; is>>t; a=t; return is;} ostream &operator<<(ostream& os, const mint& a) {return os< D; ll modpow(ll a, ll b, ll m) { if(b == 0) return 1; ll t = modpow(a, b>>1, m); return ((b&1)?a*t%m:t)*t%m; } ll gs(ll X, ll Y, ll M) { if(D.count(Y)) return D[Y]; ll R = modpow(modpow(X, M, M), M-2, M); REP(i,1,S+1) { Y = Y*R%M; if(D.count(Y)) return D[Y]+i*S; } return -1; } void solve(ll P, ll R) { ll A, B, C; cin >> A >> B >> C; ll D = ((B*B-4*A*C)%P+P)%P; if(D == 0) { ll x = -B*modpow(2*A, P-2, P); x = (x%P+P)%P; PR(x); } else { ll k = gs(R, D, P); if(k%2 == 0) { ll x1 = modpow(R, k/2, P); ll x2 = modpow(R, (k+P-1)/2, P); x1 = (-B+x1)*modpow(2*A, P-2, P); x1 = (x1%P+P)%P; x2 = (-B+x2)*modpow(2*A, P-2, P); x2 = (x2%P+P)%P; if(x1 == x2) PR(x1); else if(x1 < x2) PS(x1), PR(x2); else PS(x2), PR(x1); } else PR(-1); } } int main() { ll P, R, Q; cin >> P >> R >> Q; ll z = 1; S = sqrt(P)+1; D[1] = 0; REP(i,0,S) { z = z*R%P; D[z] = i+1; } REP(i,0,Q) solve(P, R); return 0; } /* */