#include "bits/stdc++.h" using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector veci; typedef vector vecll; typedef vector vecs; template using Hash=unordered_map; #define REP(i, a, n) for(ll i = a; i < (ll)n; i++) #define RREP(i, a, n) for(ll i = n-1; i >= (ll)a; i--) #define rep(i, n) REP(i, 0, n) #define rrep(i, n) RREP(i, 0, n) #define MD 1000000007 template T read(){T a;cin >> a;return a;} template void read(T& a){cin >> a;} template void read(T& a, Args&... args){cin >> a; read(args...);} template void rarr(T a, int n){for(int i = 0; i < n; i++) {cin >> a[i];}} template void write(T a){cout << fixed << setprecision(12) << a << endl;} template void write(T a, Args... args){cout << fixed << setprecision(4) << a << c; write(args...);} template void warr(T a, const char* c = " "){cout << a;for(int i = 1; i < (int)a.size(); i++)cout << c << a[i];cout << endl;} template void warr(T a, int n, const char* c = " "){cout << a[0];for(int i = 1; i < n; i++)cout << c << a[i];cout << endl;} void split(string s, string delim, veci& result){result.clear();string::size_type pos = 0;while(pos != string::npos){string::size_type p = s.find(delim, pos);if(p == string::npos){result.push_back(atoi(s.substr(pos).data()));break;}else {result.push_back(atoi(s.substr(pos, p - pos).data()));}pos = p + delim.size();}} void split(string s, string delim, vecs& result){result.clear();string::size_type pos = 0;while(pos != string::npos){string::size_type p = s.find(delim, pos);if(p == string::npos){result.push_back(s.substr(pos));break;}else {result.push_back(s.substr(pos, p - pos));}pos = p + delim.size();}} ull gcd(ull a, ull b){while(true){ull k = a % b;if(k == 0)return b;a = b;b = k;}} ull comb(ull n, ull m){ull p=1;m=min(m,n-m);for(ull i=1;i<=m;i++){p*=n-i+1;p/=i;}return p;} ull power( const ull& a, ull k, const ull& n ) { if ( a == 0 || n == 0 ) return( 0 ); if ( k == 0 ) return( 1 % n ); ull currentMod = a % n; ull currentValue = ( ( k & 1 ) > 0 ) ? currentMod : 1; for ( k >>= 1 ; k > 0 ; k >>= 1 ) { currentMod = ( currentMod * currentMod ) % n; if ( ( k & 1 ) > 0 ) currentValue = ( currentValue * currentMod ) % n; } return( currentValue ); } int main(void) { ll p,r,q; unordered_map mp; read(p,r,q); ll w,h; if(p<1e6){ w=h=ceil(sqrt(p)); } else { w=ceil(p/1000.0); h=1000; } rep(i,w){ int yy=power(r,i,p); mp[yy]=i; } //int i2=power(2,p-2,p); int d2p=(p-1)/2; ll irm=power(power(r,p-2,p),w,p); rep(i,q){ ll a,b,c; read(a,b,c); if(b==0&&c==0){ write(0); continue; } ll i2a=power(2*a,p-2,p); ll d=(((b*b)%p)-4*((a*c)%p))%p; if(d==0){ write(((-b+p)*i2a)%p); continue; } if(d<0)d=(d+p)%p; ll v=d; set res; rep(j,h){ auto it=mp.find(v); if(it!=mp.end()){ ll x=j*w+it->second; //write(i,x); if(x%2==0){ ll gx1=power(r,x/2,p); ll gx2=power(r,x/2+d2p,p); ll x1=(gx1-b+p)*i2a; ll x2=(gx2-b+p)*i2a; res.insert(x1%p); res.insert(x2%p); break; } } v=(v*irm)%p; } //continue; if(res.size()>0){ bool init=false; for(auto a:res){ if(init)cout<<" "; cout<