#include using namespace std; #define fst(t) std::get<0>(t) #define snd(t) std::get<1>(t) #define thd(t) std::get<2>(t) using ll = long long; template T expt(T a, T n, T mod = std::numeric_limits::max()){ T res = 1; while(n){ if(n & 1){res = res * a % mod;} a = a * a % mod; n >>= 1; } return res; } template T inverse(T n, T mod){ return expt(n, mod-2, mod); } // extgcd(a, b) = (g, s, t) // g: GCD of a and b, s, t: a solution of sa + tb = g template std::tuple extgcd(T a, T b){ if(b == 0){ return std::make_tuple(a, 1, 0); } T g, _s, _t; std::tie(g, _s, _t) = extgcd(b, a % b); return std::make_tuple(g, _t, _s - (a/b) * _t); } struct ModSqrt{ int bucket_size, bucket_n; long long p, g; std::vector> expos; std::vector invs; ModSqrt() = default; ModSqrt(long long p, long long g, int bucket_size) : p(p), g(g), bucket_size(bucket_size) { bucket_n = (p + bucket_size - 1) / bucket_size; expos = std::vector>((bucket_size + 1) / 2); expos[0] = std::make_tuple(1, 0); { long long ex = 1; for(int i=1;i<(bucket_size + 1)/2;++i){ ex = ex * g % p * g % p; expos[i] = std::make_tuple(ex, i * 2); } } std::sort(expos.begin(), expos.end()); invs = std::vector(bucket_n); long long alpha = expt(g, bucket_size, p), inv_alpha = inverse(alpha, p); invs[0] = 1ll; for(int i=0;i+1(lhs) < std::get<0>(rhs);}); if(it != expos.end() && std::get<0>(*it) == v){ long long c = i * bucket_size + std::get<1>(*it); return c; } } return -1; // no solution } long long modSqrt(long long x){ if(x % p == 0){return 0ll;} long long g, s; std::tie(g, s, std::ignore) = extgcd(2ll, p-1); long long m = babyStepGiantStep(x); if(m == -1){ return -1; } long long t = s * (m / g) % (p - 1); t = t >= 0 ? t : t + (p - 1); return expt(g, t, p); } }; ModSqrt modSqrt; int ti; ll P, R; int main(){ std::cin.tie(nullptr); std::ios::sync_with_stdio(false); ti = 12; scanf("%lld %lld", &P, &R); modSqrt = std::move(ModSqrt(P, R, (int)std::sqrt(P) * ti)); int Q; scanf("%d", &Q); for(int i=0;i= 0 ? D : D + P; ll sq = modSqrt.modSqrt(D); if(sq == -1){puts("-1"); continue;} ll den = inverse(2ll * a % P, P); ll x0 = (-b - sq) * den % P, x1 = (-b + sq) * den % P; x0 = x0 >= 0 ? x0 : x0 + P; x1 = x1 >= 0 ? x1 : x1 + P; if(x0 > x1){swap(x0, x1);} if(x0 == x1){ printf("%lld\n", x0); }else{ printf("%lld %lld\n", x0, x1); } } }