#include using namespace std; typedef long long LL; #define CIN_ONLY if(1) struct cww{cww(){ CIN_ONLY{ ios::sync_with_stdio(false);cin.tie(0); } }}star; #define fin "\n" #define FOR(i,bg,ed) for(int i=(bg);i<(ed);i++) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() #define fi first #define se second #define pb push_back #define DEBUG if(0) #define REC(ret, ...) std::function template inline bool chmin(T &l,T r) {bool a=l>r;if(a)l=r;return a;} template inline bool chmax(T &l,T r) {bool a=l istream& operator>>(istream &is,vector &v){ for(auto &it:v)is>>it; return is; } const int H=2523456; const int h=412; unordered_map giant[1024]; void giant_step(LL g,int p){ LL gg=1; REP(i,h)gg=gg*g%p; LL ggg=1; REP(i,H){ LL key=ggg; LL val=h*i%(p-1); LL id=key&1023; if(giant[id].count(key)==1)return; giant[id][key]=val; ggg=ggg*gg%p; } } LL baby_step(LL key,LL r,int p){ REP(i,h){ LL id=key&1023; if(giant[id].count(key)){ LL ah=giant[id][key]; return (ah-i+p-1)%(p-1); } key=key*r%p; } return -1; } // a x + b y = gcd(a, b) // O(log (a+b) ) LL extgcd(LL a, LL b, LL &x, LL &y) { LL g = a; x = 1; y = 0; if (b != 0) g = extgcd(b, a % b, y, x), y -= (a / b) * x; return g; } // mを法とするaの逆元 // O(log a) LL invMod(LL a,int MOD) { LL x, y; if (extgcd(a, MOD, x, y) == 1)return (x + MOD) % MOD; else return 0; // unsolvable } LL pow_mod(LL a,LL n,int MOD){ LL res=1; LL b=1; a%=MOD; while(n>=b){ if(n&b) res=(res*a)%MOD; a=(a*a)%MOD; b<<=1; } return res; } LL getX(LL g,int p,LL XX){ if(XX==0)return 0; LL x=baby_step(XX,g,p); if(x%2==0)return pow_mod(g,x/2,p); else return -1; } int main(){ int P,Q,R; cin>>P>>R>>Q; giant_step(R,P); REP(i,Q){ LL a,b,c; cin>>a>>b>>c; LL sq=getX(R,P,(b*b%P+P-4*a*c%P)%P); if(sq==-1)cout<<-1<y)cout<