結果

問題 No.981 一般冪乗根
ユーザー PachicobuePachicobue
提出日時 2020-02-08 17:15:28
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 3,274 ms / 6,000 ms
コード長 33,739 bytes
コンパイル時間 2,952 ms
コンパイル使用メモリ 232,664 KB
実行使用メモリ 10,024 KB
最終ジャッジ日時 2024-10-09 21:00:31
合計ジャッジ時間 173,156 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3,096 ms
9,888 KB
testcase_01 AC 3,097 ms
9,888 KB
testcase_02 AC 3,259 ms
10,016 KB
testcase_03 AC 3,068 ms
10,016 KB
testcase_04 AC 3,068 ms
9,892 KB
testcase_05 AC 71 ms
9,892 KB
testcase_06 AC 72 ms
9,888 KB
testcase_07 AC 73 ms
9,888 KB
testcase_08 AC 72 ms
9,892 KB
testcase_09 AC 72 ms
10,024 KB
testcase_10 AC 73 ms
9,896 KB
testcase_11 AC 72 ms
9,888 KB
testcase_12 AC 72 ms
10,016 KB
testcase_13 AC 72 ms
6,820 KB
testcase_14 AC 73 ms
6,816 KB
testcase_15 AC 72 ms
6,816 KB
testcase_16 AC 73 ms
6,820 KB
testcase_17 AC 72 ms
6,816 KB
testcase_18 AC 72 ms
6,820 KB
testcase_19 AC 73 ms
6,816 KB
testcase_20 AC 72 ms
6,820 KB
testcase_21 AC 72 ms
6,816 KB
testcase_22 AC 72 ms
6,816 KB
testcase_23 AC 71 ms
6,816 KB
testcase_24 AC 73 ms
6,820 KB
testcase_25 AC 3,080 ms
6,816 KB
testcase_26 AC 3,274 ms
6,820 KB
testcase_27 AC 4 ms
6,820 KB
testcase_28 AC 2,961 ms
6,816 KB
evil_60bit1.txt TLE -
evil_60bit2.txt TLE -
evil_60bit3.txt TLE -
evil_hack AC 3 ms
6,816 KB
evil_hard_random TLE -
evil_hard_safeprime.txt TLE -
evil_hard_tonelli0 TLE -
evil_hard_tonelli1 TLE -
evil_hard_tonelli2 TLE -
evil_hard_tonelli3 TLE -
evil_sefeprime1.txt TLE -
evil_sefeprime2.txt TLE -
evil_sefeprime3.txt TLE -
evil_tonelli1.txt TLE -
evil_tonelli2.txt TLE -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wsign-conversion"

using i32   = int32_t;
using i64   = int64_t;
using u32   = uint32_t;
using u64   = uint64_t;
using uint  = unsigned int;
using usize = std::size_t;
using ll    = long long;
using ull   = unsigned long long;
using ld    = long double;
template<typename T, usize n>
using arr = T (&)[n];
template<typename T, usize n>
using c_arr = const T (&)[n];
template<typename T>
using max_heap = std::priority_queue<T>;
template<typename T>
using min_heap = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template<typename T> constexpr T popcount(const T u) { return u ? static_cast<T>(__builtin_popcountll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T log2p1(const T u) { return u ? static_cast<T>(64 - __builtin_clzll(static_cast<u64>(u))) : static_cast<T>(0); }
template<typename T> constexpr T msbp1(const T u) { return log2p1(u); }
template<typename T> constexpr T lsbp1(const T u) { return __builtin_ffsll(u); }
template<typename T> constexpr T clog(const T u) { return u ? log2p1(u - 1) : static_cast<T>(u); }
template<typename T> constexpr bool ispow2(const T u) { return u and (static_cast<u64>(u) & static_cast<u64>(u - 1)) == 0; }
template<typename T> constexpr T ceil2(const T u) { return static_cast<T>(1) << clog(u); }
template<typename T> constexpr T floor2(const T u) { return u == 0 ? static_cast<T>(0) : static_cast<T>(1) << (log2p1(u) - 1); }
template<typename T> constexpr bool btest(const T mask, const usize ind) { return static_cast<bool>((static_cast<u64>(mask) >> ind) & static_cast<u64>(1)); }
template<typename T> void bset(T& mask, const usize ind) { mask |= (static_cast<T>(1) << ind); }
template<typename T> void breset(T& mask, const usize ind) { mask &= ~(static_cast<T>(1) << ind); }
template<typename T> void bflip(T& mask, const usize ind) { mask ^= (static_cast<T>(1) << ind); }
template<typename T> void bset(T& mask, const usize ind, const bool b) { (b ? bset(mask, ind) : breset(mask, ind)); }
template<typename T> constexpr T bcut(const T mask, const usize ind) { return ind == 0 ? static_cast<T>(0) : static_cast<T>((static_cast<u64>(mask) << (64 - ind)) >> (64 - ind)); }
template<typename T> bool chmin(T& a, const T& b) { return (a > b ? a = b, true : false); }
template<typename T> bool chmax(T& a, const T& b) { return (a < b ? a = b, true : false); }
constexpr unsigned int mod                  = 1000000007;
template<typename T> constexpr T inf_v      = std::numeric_limits<T>::max() / 4;
template<typename Real> constexpr Real pi_v = Real{3.141592653589793238462643383279502884};
auto mfp = [](auto&& f) { return [=](auto&&... args) { return f(f, std::forward<decltype(args)>(args)...); }; };

template<typename T>
T in()
{
    T v;
    return std::cin >> v, v;
}
template<typename T, typename Uint, usize n, usize i>
T in_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type) { return in<T>(); }
template<typename T, typename Uint, usize n, usize i>
auto in_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type& szs)
{
    const usize s = (usize)szs[i];
    std::vector<decltype(in_v<T, Uint, n, i + 1>(szs))> ans(s);
    for (usize j = 0; j < s; j++) { ans[j] = in_v<T, Uint, n, i + 1>(szs); }
    return ans;
}
template<typename T, typename Uint, usize n>
auto in_v(c_arr<Uint, n> szs) { return in_v<T, Uint, n, 0>(szs); }
template<typename... Types>
auto in_t() { return std::tuple<std::decay_t<Types>...>{in<Types>()...}; }
struct io_init
{
    io_init()
    {
        std::cin.tie(nullptr), std::ios::sync_with_stdio(false);
        std::cout << std::fixed << std::setprecision(20);
    }
    void clear()
    {
        std::cin.tie(), std::ios::sync_with_stdio(true);
    }
} io_setting;

int out() { return 0; }
template<typename T>
int out(const T& v) { return std::cout << v, 0; }
template<typename T>
int out(const std::vector<T>& v)
{
    for (usize i = 0; i < v.size(); i++) {
        if (i > 0) { std::cout << ' '; }
        out(v[i]);
    }
    return 0;
}
template<typename T1, typename T2>
int out(const std::pair<T1, T2>& v) { return out(v.first), std::cout << ' ', out(v.second), 0; }
template<typename T, typename... Args>
int out(const T& v, const Args... args) { return out(v), std::cout << ' ', out(args...), 0; }
template<typename... Args>
int outln(const Args... args) { return out(args...), std::cout << '\n', 0; }
template<typename... Args>
int outel(const Args... args) { return out(args...), std::cout << std::endl, 0; }
#    define SHOW(...) static_cast<void>(0)
constexpr ull TEN(const usize n) { return n == 0 ? 1ULL : TEN(n - 1) * 10ULL; }

template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i == n), c_arr<Uint, n>>::type, const T& v = T{}) { return v; }
template<typename T, typename Uint, usize n, usize i>
auto make_v(typename std::enable_if<(i < n), c_arr<Uint, n>>::type szs, const T& v = T{})
{
    const usize s = (usize)szs[i];
    return std::vector<decltype(make_v<T, Uint, n, i + 1>(szs, v))>(s, make_v<T, Uint, n, i + 1>(szs, v));
}
template<typename T, typename Uint, usize n>
auto make_v(c_arr<Uint, n> szs, const T& t = T{}) { return make_v<T, Uint, n, 0>(szs, t); }


template<typename T> T gcd(const T& a, const T& b) { return a < 0 ? gcd(-a, b) : b < 0 ? gcd(a, -b) : (a > b ? gcd(b, a) : a == 0 ? b : gcd(b % a, a)); }
template<typename T> T lcm(const T& a, const T& b) { return a / gcd(a, b) * b; }
template<typename T>
constexpr std::pair<T, T> extgcd(const T a, const T b)
{
    if (b == 0) { return std::pair<T, T>{1, 0}; }
    const auto g = gcd(a, b), da = std::abs(b) / g;
    const auto p = extgcd(b, a % b);
    const auto x = (da + p.second % da) % da, y = (g - a * x) / b;
    return {x, y};
}
template<typename T>
constexpr T inverse(const T a, const T mod) { return extgcd(a, mod).first; }
template<uint mod_value, bool dynamic = false>
class modint_base
{
public:
    template<typename UInt = uint>
    static std::enable_if_t<dynamic, const UInt> mod() { return mod_ref(); }
    template<typename UInt = uint>
    static constexpr std::enable_if_t<not dynamic, const UInt> mod() { return mod_value; }
    template<typename UInt = uint>
    static void set_mod(const std::enable_if_t<dynamic, const UInt> mod) { mod_ref() = mod, inv_ref() = {1, 1}; }
    modint_base() : v{0} {}
    modint_base(const ll val) : v{norm(static_cast<uint>(val % static_cast<ll>(mod()) + static_cast<ll>(mod())))} {}
    modint_base(const modint_base& n) : v{n()} {}
    explicit operator bool() const { return v != 0; }
    bool operator!() const { return not static_cast<bool>(*this); }
    modint_base& operator=(const modint_base& m) { return v = m(), (*this); }
    modint_base& operator=(const ll val) { return v = norm(uint(val % static_cast<ll>(mod()) + static_cast<ll>(mod()))), (*this); }
    friend modint_base operator+(const modint_base& m) { return m; }
    friend modint_base operator-(const modint_base& m) { return make(norm(mod() - m.v)); }
    friend modint_base operator+(const modint_base& m1, const modint_base& m2) { return make(norm(m1.v + m2.v)); }
    friend modint_base operator-(const modint_base& m1, const modint_base& m2) { return make(norm(m1.v + mod() - m2.v)); }
    friend modint_base operator*(const modint_base& m1, const modint_base& m2) { return make(static_cast<uint>(static_cast<ll>(m1.v) * static_cast<ll>(m2.v) % static_cast<ll>(mod()))); }
    friend modint_base operator/(const modint_base& m1, const modint_base& m2) { return m1 * inv(m2.v); }
    friend modint_base operator+(const modint_base& m, const ll val) { return modint_base{static_cast<ll>(m.v) + val}; }
    friend modint_base operator-(const modint_base& m, const ll val) { return modint_base{static_cast<ll>(m.v) - val}; }
    friend modint_base operator*(const modint_base& m, const ll val) { return modint_base{static_cast<ll>(m.v) * (val % static_cast<ll>(mod()))}; }
    friend modint_base operator/(const modint_base& m, const ll val) { return modint_base{static_cast<ll>(m.v) * inv(val)}; }
    friend modint_base operator+(const ll val, const modint_base& m) { return modint_base{static_cast<ll>(m.v) + val}; }
    friend modint_base operator-(const ll val, const modint_base& m) { return modint_base{-static_cast<ll>(m.v) + val}; }
    friend modint_base operator*(const ll val, const modint_base& m) { return modint_base{static_cast<ll>(m.v) * (val % static_cast<ll>(mod()))}; }
    friend modint_base operator/(const ll val, const modint_base& m) { return modint_base{val * inv(static_cast<ll>(m.v))}; }
    friend modint_base& operator+=(modint_base& m1, const modint_base& m2) { return m1 = m1 + m2; }
    friend modint_base& operator-=(modint_base& m1, const modint_base& m2) { return m1 = m1 - m2; }
    friend modint_base& operator*=(modint_base& m1, const modint_base& m2) { return m1 = m1 * m2; }
    friend modint_base& operator/=(modint_base& m1, const modint_base& m2) { return m1 = m1 / m2; }
    friend modint_base& operator+=(modint_base& m, const ll val) { return m = m + val; }
    friend modint_base& operator-=(modint_base& m, const ll val) { return m = m - val; }
    friend modint_base& operator*=(modint_base& m, const ll val) { return m = m * val; }
    friend modint_base& operator/=(modint_base& m, const ll val) { return m = m / val; }
    friend modint_base operator^(const modint_base& m, const ll n) { return power(m.v, n); }
    friend modint_base& operator^=(modint_base& m, const ll n) { return m = m ^ n; }
    friend bool operator==(const modint_base& m1, const modint_base& m2) { return m1.v == m2.v; }
    friend bool operator!=(const modint_base& m1, const modint_base& m2) { return not(m1 == m2); }
    friend bool operator==(const modint_base& m, const ll val) { return m.v == norm(static_cast<uint>(static_cast<ll>(mod()) + val % static_cast<ll>(mod()))); }
    friend bool operator!=(const modint_base& m, const ll val) { return not(m == val); }
    friend bool operator==(const ll val, const modint_base& m) { return m.v == norm(static_cast<uint>(static_cast<ll>(mod()) + val % static_cast<ll>(mod()))); }
    friend bool operator!=(const ll val, const modint_base& m) { return not(m == val); }
    friend std::istream& operator>>(std::istream& is, modint_base& m)
    {
        ll v;
        return is >> v, m = v, is;
    }
    friend std::ostream& operator<<(std::ostream& os, const modint_base& m) { return os << m(); }
    uint operator()() const { return v; }
    static modint_base small_inv(const usize n)
    {
        auto& in = inv_ref();
        if (n < in.size()) { return in[n]; }
        for (usize i = in.size(); i <= n; i++) { in.push_back(-in[modint_base::mod() % i] * (modint_base::mod() / i)); }
        return in.back();
    }
    std::pair<ll, ll> quad() const
    {
        const auto ans = quad_r(v, mod());
        ll x = std::get<0>(ans), y = std::get<1>(ans);
        if (y < 0) { x = -x, y = -y; }
        return {x, y};
    }

private:
    static std::tuple<ll, ll, ll> quad_r(const ll r, const ll p)  // r = x/y (mod p), (x,y,z) s.t. x=yr+pz
    {
        if (std::abs(r) <= 1000) { return {r, 1, 0}; }
        ll nr = p % r, q = p / r;
        if (nr * 2LL >= r) { nr -= r, q++; }
        if (nr * 2LL <= -r) { nr += r, q--; }
        const auto sub = quad_r(nr, r);
        const ll x = std::get<0>(sub), z = std::get<1>(sub), y = std::get<2>(sub);
        return {x, y - q * z, z};
    }

    template<typename UInt = uint>
    static std::enable_if_t<dynamic, UInt&> mod_ref()
    {
        static UInt mod = 0;
        return mod;
    }
    static uint norm(const uint x) { return x < mod() ? x : x - mod(); }
    static modint_base make(const uint x)
    {
        modint_base m;
        return m.v = x, m;
    }
    static modint_base power(modint_base x, ull n)
    {
        modint_base ans = 1;
        for (; n; n >>= 1, x *= x) {
            if (n & 1) { ans *= x; }
        }
        return ans;
    }
    static modint_base inv(const ll v) { return v <= 2000000 ? small_inv(static_cast<usize>(v)) : modint_base{inverse(v, static_cast<ll>(mod()))}; }
    static std::vector<modint_base>& inv_ref()
    {
        static std::vector<modint_base> in{1, 1};
        return in;
    }
    uint v;
};
template<uint mod>
using modint = modint_base<mod, false>;
template<uint id>
using dynamic_modint = modint_base<id, true>;




class xoshiro
{
public:
    using result_type = uint32_t;
    static constexpr result_type min() { return std::numeric_limits<result_type>::min(); }
    static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
    xoshiro() : xoshiro(std::random_device{}()) {}
    xoshiro(uint64_t seed)
    {
        uint64_t z = 0;
        for (int i = 0; i < 4; i++) { z = (seed += 0x9e3779b97f4a7c15), z = (z ^ (z >> 33)) * 0x62A9D9ED799705F5, z = (z ^ (z >> 28)) * 0xCB24D0A5C88C35B3, s[i] = static_cast<result_type>(z >> 32); }
    }
    result_type operator()()
    {
        const result_type result = rotl(s[1] * 5, 7) * 9, t = s[1] << 9;
        return s[2] ^= s[0], s[3] ^= s[1], s[1] ^= s[2], s[0] ^= s[3], s[2] ^= t, s[3] = rotl(s[3], 11), result;
    }
    void discard(const usize rep)
    {
        for (usize i = 0; i < rep; i++) { (*this)(); }
    }

private:
    result_type s[4];
    static result_type rotl(const result_type x, const int k) { return (x << k) | (x >> (32 - k)); }
};
class xoshiro_64
{
public:
    using result_type = uint64_t;
    static constexpr result_type min() { return std::numeric_limits<result_type>::min(); }
    static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
    xoshiro_64() : xoshiro_64(std::random_device{}()) {}
    xoshiro_64(uint64_t seed)
    {
        uint64_t z = 0;
        for (int i = 0; i < 4; i++) { z = (seed += 0x9e3779b97f4a7c15), z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9, z = (z ^ (z >> 27)) * 0x94d049bb133111eb, s[i] = static_cast<result_type>(z ^ (z >> 31)); }
    }
    result_type operator()()
    {
        const result_type result = rotl(s[1] * 5, 7) * 9, t = s[1] << 17;
        return s[2] ^= s[0], s[3] ^= s[1], s[1] ^= s[2], s[0] ^= s[3], s[2] ^= t, s[3] = rotl(s[3], 45), result;
    }
    void discard(const usize rep)
    {
        for (usize i = 0; i < rep; i++) { (*this)(); }
    }

private:
    result_type s[4];
    static result_type rotl(const result_type x, const int k) { return (x << k) | (x >> (64 - k)); }
};
template<typename Rng>
class rng_base
{
public:
    using rng_type    = Rng;
    using result_type = typename rng_type::result_type;
    static constexpr result_type min() { return rng_type::min(); }
    static constexpr result_type max() { return rng_type::max(); }
    rng_base() : rng_base(std::random_device{}()) {}
    rng_base(const u64 seed) : rng(seed) {}
    ~rng_base() = default;
    result_type operator()(const result_type max = std::numeric_limits<result_type>::max())
    {
        if (max == std::numeric_limits<result_type>::max()) { return static_cast<result_type>(rng()); }
        if (ispow2(max + 1)) { return static_cast<result_type>(rng() & max); }
        const result_type mask = static_cast<result_type>(ceil2(static_cast<u64>(max + 1))) - 1;
        while (true) {
            const result_type ans = static_cast<result_type>(rng() & mask);
            if (ans <= max) { return ans; }
        }
    }
    template<typename Int = result_type>
    Int operator()(const Int min, const Int max) { return min + (Int)(*this)(max - min); }
    operator bool() { return (bool)(*this)(0, 1); }
    template<typename Int> std::pair<Int, Int> pair(const Int min, const Int max) { return std::pair<Int, Int>{*this(min, max), *this(min, max)}; }
    template<typename Int>
    std::vector<Int> vec(const usize n, const Int min, const Int max)
    {
        std::vector<Int> v(n);
        for (usize i = 0; i < n; i++) { v[i] = (*this)(min, max); }
        return v;
    }
    std::vector<usize> perm(const usize n)
    {
        std::vector<usize> ans(n);
        std::iota(ans.begin(), ans.end(), 0UL);
        std::shuffle(ans.begin(), ans.end(), rng);
        return ans;
    }

private:
    Rng rng;
};
using rng_mt        = rng_base<std::mt19937>;
using rng_mt64      = rng_base<std::mt19937_64>;
using rng_xoshiro   = rng_base<xoshiro>;
using rng_xoshiro64 = rng_base<xoshiro_64>;
rng_mt g_rng_mt;
rng_mt64 g_rng_mt64;
rng_xoshiro g_rng_xo;
rng_xoshiro64 g_rng_xo64;
template<typename T, typename V>
inline bool miller_rabin(const T& n, const std::vector<T>& as)
{
    auto pow = [&](auto&& self, const V& a, const T k) -> V {
        if (k == 0) { return 1; }
        if (k % 2 == 0) {
            return self(self, (a * a) % V(n), k / 2);
        } else {
            return (self(self, a, k - 1) * a) % V(n);
        }
    };
    T d = n - 1;
    for (; (d & 1) == 0; d >>= 1) {}
    for (const T& a : as) {
        if (n <= a) { break; }
        T s = d;
        V x = pow(pow, a, s);
        while (x != 1 and x != n - 1 and s != n - 1) {
            (x *= x) %= V(n);
            s *= 2;
        }
        if (x != n - 1 and s % 2 == 0) { return false; }
    }
    return true;
}
template<typename T>
inline bool is_prime(const T& n, const usize trial)
{
    if (n % 2 == 0) { return n == 2; }
    std::vector<T> as(trial);
    for (usize i = 0; i < trial; i++) { as[i] = static_cast<T>(g_rng_xo64(T{2}, n - 2)); }
    return miller_rabin<T, T>(n, as);
}
inline bool is_prime(const ull n)
{
    if (n % 2 == 0) { return n == 2; }
    if (n < (1ULL << 32)) {
        return miller_rabin<uint, ull>((uint)n, std::vector<uint>{2, 7, 61});
    } else {
        return miller_rabin<ull, __uint128_t>(n, std::vector<ull>{2, 325, 9375, 28178, 450775, 9780504});
    }
}
template<typename T, typename V = T>
T pollard_rho(const T n)
{
    if (n % 2 == 0) { return 2; }
    if (is_prime(n)) { return n; }
    for (T c = 1; c < n; c++) {
        if (c == n - 2) { continue; }
        auto f = [&](const T x) -> T { return T((V(x) * V(x) + V(c)) % V(n)); };
        T x = 2, y = 2, d = 1;
        while (d == 1) {
            x = f(x), y = f(f(y));
            d = gcd(std::max(x, y) - std::min(x, y), n);
        }
        if (d != n) { return d; }
    }
    return n;
}
std::map<ull, usize> prime_factors(const ull n)
{
    std::map<ull, usize> ans;
    auto factor = [&](auto&& self, const ull n) -> void {
        if (n == 1) { return; }
        const ull p = (n < (1ULL << 32)) ? (ull)pollard_rho<uint, ull>((uint)n) : pollard_rho<ull, __uint128_t>(n);
        if (p == n) {
            ans[p]++;
            return;
        }
        self(self, p);
        self(self, n / p);
    };
    factor(factor, n);
    return ans;
}

template<typename T>
std::pair<T, T> crt(const std::pair<T, T>& a1, const std::pair<T, T>& a2)
{
    using P = std::pair<T, T>;
    T r1 = a1.first, m1 = a1.second, r2 = a2.first, m2 = a2.second;
    const T g = gcd(m1, m2);
    if (r1 % g != r2 % g) { return P{0, 0}; }
    const T m = m1 / g * m2;
    if (r1 == r2) { return {r1, m}; }
    const auto k1 = extgcd(m1, m2).first * ((r2 - r1) / g) % (m2 / g);
    return P{(m + (m1 * k1 % m) + r1) % m, m};
}
template<typename T, typename InIt>
std::pair<T, T> crt(const InIt first, const InIt last)
{
    using P = std::pair<T, T>;
    return std::accumulate(first, last, P{0, 1}, [](const P& a1, const P& a2) -> P { return crt(a1, a2); });
}
using namespace std;
template<class _Key, class _Tp, class _Hash, bool DOWNSIZE> class UnorderedMapIterator;

template<class _Key, class _Tp, class _Hash = hash<_Key>, bool DOWNSIZE = false>
class UnorderedMap
{
private:
    using iterator        = UnorderedMapIterator<_Key, _Tp, _Hash, DOWNSIZE>;
    using value_type      = _Tp;
    using data_type       = pair<_Key, _Tp>;
    using aligned_pointer = typename aligned_storage<sizeof(value_type), alignof(value_type)>::type;
    friend UnorderedMapIterator<_Key, _Tp, _Hash, DOWNSIZE>;
    struct bucket
    {
        _Key _key;
        short int _dist;
        bool _last, _end;
        aligned_pointer _value_ptr;
        bucket() noexcept : _dist(-1), _last(false), _end(false) {}
        bucket& operator=(const bucket& another) noexcept
        {
            _key = another._key, _dist = another._dist, _last = another._last, _end = another._end;
            if (!another.empty()) {
                new (&_value_ptr) value_type(*reinterpret_cast<const value_type*>(&another._value_ptr));
            }
            return *this;
        }
        ~bucket()
        {
            if (!empty()) _delete();
        }
        inline void clear() noexcept { _dist = -1; }
        inline void _delete() { _dist = -1, value_ptr()->~value_type(); }
        inline bool empty() const noexcept { return (_dist == -1); }
        inline value_type& value() noexcept
        {
            return *reinterpret_cast<value_type*>(&_value_ptr);
        }
        inline value_type* value_ptr() noexcept
        {
            return reinterpret_cast<value_type*>(&_value_ptr);
        }
        inline void new_value(value_type&& value)
        {
            new (&_value_ptr) value_type(move(value));
        }
    };
    inline static unsigned int ceilpow2(unsigned int u) noexcept
    {
        if (u == 0u) return 0u;
        --u, u |= u >> 1, u |= u >> 2, u |= u >> 4, u |= u >> 8;
        return (u | (u >> 16)) + 1u;
    }
    inline static bucket* increment(bucket* cur) noexcept
    {
        for (++cur; !cur->_end; ++cur) {
            if (!cur->empty()) break;
        }
        return cur;
    }
    inline bucket* next_bucket(bucket* cur) const noexcept
    {
        return cur->_last ? _buckets : cur + 1;
    }
    inline unsigned int make_hash(const _Key& key) const noexcept
    {
        return _Hash()(key);
    }
    inline float load_rate() const noexcept
    {
        return (float)_data_count / _bucket_count;
    }
    bucket* insert(bucket* cur, _Key&& key, short int dist, value_type&& value)
    {
        bucket* ret = cur;
        bool flag   = false;
        while (true) {
            if (cur->empty()) {
                cur->_key = move(key), cur->_dist = dist, cur->new_value(move(value));
                if (!flag) ret = cur, flag = true;
                break;
            } else if (dist > cur->_dist) {
                swap(key, cur->_key), swap(dist, cur->_dist), swap(value, cur->value());
                if (!flag) ret = cur, flag = true;
            }
            ++dist;
            cur = next_bucket(cur);
        }
        return ret;
    }
    template<class Key>
    bucket* _find(Key&& key, bool push = false)
    {
        unsigned int hash = make_hash(key);
        bucket* cur       = _buckets + (hash & _mask);
        short int dist    = 0;
        while (dist <= cur->_dist) {
            if (key == cur->_key) return cur;
            ++dist, cur = next_bucket(cur);
        }
        if (!push) return _buckets + _bucket_count;
        ++_data_count;
        if (rehash_check()) {
            cur = _buckets + (hash & _mask), dist = 0;
        }
        value_type new_value = value_type();
        _Key new_key         = forward<Key>(key);
        return insert(cur, move(new_key), dist, move(new_value));
    }
    template<class Data>
    bucket* find_insert(Data&& data)
    {
        const _Key& key   = data.first;
        unsigned int hash = make_hash(key);
        bucket* cur       = _buckets + (hash & _mask);
        short int dist    = 0;
        while (dist <= cur->_dist) {
            if (key == cur->_key) return cur;
            ++dist, cur = next_bucket(cur);
        }
        ++_data_count;
        if (rehash_check()) {
            cur = _buckets + (hash & _mask), dist = 0;
        }
        data_type new_data = forward<Data>(data);
        return insert(cur, move(new_data.first), dist, move(new_data.second));
    }
    template<typename... Args>
    bucket* emplace(Args&&... args)
    {
        return find_insert(data_type(forward<Args>(args)...));
    }
    bucket* backward_shift(bucket* cur, bool next_ret)
    {
        bucket *next = next_bucket(cur), *ret = cur;
        if (next->_dist < 1) return next_ret ? increment(cur) : cur;
        do {
            cur->_key = next->_key, cur->_dist = next->_dist - 1;
            cur->new_value(move(next->value()));
            cur = next, next = next_bucket(cur);
        } while (next->_dist >= 1);
        cur->clear();
        return ret;
    }
    bucket* erase_impl(bucket* cur, bool next_ret)
    {
        assert(static_cast<size_t>(cur - _buckets) != _bucket_count);
        cur->_delete();
        --_data_count;
        return backward_shift(cur, next_ret);
    }
    bucket* erase_itr(bucket* cur, bool next_ret = true)
    {
        const _Key key = cur->_key;
        return erase_impl(rehash_check() ? _find(key) : cur, next_ret);
    }
    bucket* erase_key(const _Key& key, bool next_ret = true)
    {
        rehash_check();
        return erase_impl(_find(key), next_ret);
    }
    bool rehash_check()
    {
        if (_bucket_count == 0) {
            rehash(1u);
            return true;
        } else if (load_rate() >= MAX_LOAD_RATE) {
            rehash(_bucket_count * 2u);
            return true;
        } else if (DOWNSIZE) {
            if (load_rate() <= MIN_LOAD_RATE && _bucket_count >= DOWNSIZE_THRESHOLD) {
                rehash(_bucket_count / 2u);
                return true;
            }
        }
        return false;
    }
    void move_data(bucket* cur)
    {
        insert(_buckets + (make_hash(cur->_key) & _mask), move(cur->_key), 0, move(cur->value()));
    }
    void rehash(unsigned int new_bucket_count)
    {
        UnorderedMap new_unordered_map(new_bucket_count);
        new_unordered_map._data_count = _data_count;
        for (bucket* cur = _buckets; !cur->_end; ++cur) {
            if (!cur->empty()) {
                new_unordered_map.move_data(cur);
            }
        }
        swap(*this, new_unordered_map);
    }
    friend void swap(UnorderedMap& ump1, UnorderedMap& ump2)
    {
        swap(ump1._bucket_count, ump2._bucket_count);
        swap(ump1._mask, ump2._mask);
        swap(ump1._data_count, ump2._data_count);
        swap(ump1._buckets, ump2._buckets);
    }

private:
    unsigned int _bucket_count, _mask, _data_count;
    bucket* _buckets;

public:
    const float MAX_LOAD_RATE             = 0.5f;
    const float MIN_LOAD_RATE             = 0.1f;
    const unsigned int DOWNSIZE_THRESHOLD = 16u;
    UnorderedMap(unsigned int bucket_size = 0u)
        : _bucket_count(ceilpow2(bucket_size)), _mask(_bucket_count - 1), _data_count(0u), _buckets(new bucket[_bucket_count + 1])
    {
        if (_bucket_count > 0)
            _buckets[_bucket_count - 1]._last = true;
        else
            _mask = 0;
        _buckets[_bucket_count]._end = true;
    }
    UnorderedMap(const UnorderedMap& another)
        : _bucket_count(another._bucket_count), _mask(another._mask), _data_count(another._data_count)
    {
        _buckets = new bucket[_bucket_count + 1u];
        for (unsigned int i = 0u; i <= _bucket_count; ++i) {
            _buckets[i] = another._buckets[i];
        }
    }
    UnorderedMap(UnorderedMap&& another)
        : _bucket_count(move(another._bucket_count)), _mask(move(another._mask)), _data_count(move(another._data_count)), _buckets(another._buckets)
    {
        another._buckets = nullptr;
    }
    UnorderedMap& operator=(const UnorderedMap& another)
    {
        delete[] _buckets;
        _bucket_count = another._bucket_count;
        _mask         = another._mask;
        _data_count   = another._data_count;
        _buckets      = new bucket[_bucket_count + 1u];
        for (unsigned int i = 0u; i <= _bucket_count; ++i) {
            _buckets[i] = another._buckets[i];
        }
        return *this;
    }
    UnorderedMap& operator=(UnorderedMap&& another)
    {
        delete[] _buckets;
        _bucket_count    = move(another._bucket_count);
        _mask            = move(another._mask);
        _data_count      = move(another._data_count);
        _buckets         = another._buckets;
        another._buckets = nullptr;
        return *this;
    }
    void allocate(unsigned int element_size)
    {
        rehash(ceilpow2(ceil(element_size / MAX_LOAD_RATE) + 1));
    }
    ~UnorderedMap() { delete[] _buckets; }
    friend ostream& operator<<(ostream& os, UnorderedMap& ump) noexcept
    {
        for (auto val : ump) os << '{' << val.first << ',' << val.second << "} ";
        return os;
    }
    _Tp& operator[](const _Key& key) { return _find(key, true)->value(); }
    _Tp& operator[](_Key&& key) { return _find(move(key), true)->value(); }
    const _Tp& at(const _Key& key)
    {
        bucket* res = _find(key);
        if (res == _buckets + _bucket_count) __throw_out_of_range(__N("Unordered_Map::at"));
        return res->value();
    }
    void clear()
    {
        UnorderedMap new_unordered_map(1u);
        swap(*this, new_unordered_map);
    }
    size_t size() const noexcept { return _data_count; }
    size_t bucket_count() const noexcept { return _bucket_count; }
    bool empty() const noexcept { return (_data_count == 0); }
    iterator begin() noexcept
    {
        return (_buckets->empty() && _bucket_count > 0) ? iterator(increment(_buckets)) : iterator(_buckets);
    }
    iterator end() noexcept { return iterator(_buckets + _bucket_count); }
    iterator find(const _Key& key) { return iterator(_find(key)); }
    iterator insert(const data_type& data) { return iterator(find_insert(data)); }
    iterator insert(data_type&& data) { return iterator(find_insert(move(data))); }
    template<typename... Args>
    iterator emplace(Args&&... args) { return iterator(_emplace(forward<Args>(args)...)); }
    iterator erase(const _Key& key) { return iterator(erase_key(key)); }
    iterator erase(const iterator& itr) { return iterator(erase_itr(itr.bucket_ptr)); }
    void simple_erase(const _Key& key) { erase_key(key, false); }
    void simple_erase(const iterator& itr) { erase_itr(itr.bucket_ptr, false); }

    // DEBUG 用
    short int maximum_distance() const noexcept
    {
        short int ret = -1;
        for (bucket* cur = _buckets; !cur->_end; ++cur) {
            ret = max(ret, cur->_dist);
        }
        return ret;
    }
};

template<class _Key, class _Tp, class _Hash, bool DOWNSIZE>
class UnorderedMapIterator
{
private:
    friend UnorderedMap<_Key, _Tp, _Hash, DOWNSIZE>;
    typename UnorderedMap<_Key, _Tp, _Hash, DOWNSIZE>::bucket* bucket_ptr;
    using iterator_category = forward_iterator_tag;
    using value_type        = pair<const _Key, _Tp>;
    using difference_type   = ptrdiff_t;
    using reference         = pair<const _Key&, _Tp&>;

private:
    UnorderedMapIterator(typename UnorderedMap<_Key, _Tp, _Hash, DOWNSIZE>::bucket* _bucket_ptr) noexcept : bucket_ptr(_bucket_ptr) {}

public:
    UnorderedMapIterator() noexcept : bucket_ptr() {}
    UnorderedMapIterator(const UnorderedMapIterator& itr) noexcept : bucket_ptr(itr.bucket_ptr) {}
    UnorderedMapIterator& operator=(const UnorderedMapIterator& itr)
        & noexcept { return bucket_ptr = itr.bucket_ptr, *this; }
    UnorderedMapIterator& operator=(const UnorderedMapIterator&& itr)
        & noexcept { return bucket_ptr = itr.bucket_ptr, *this; }
    reference operator*() const noexcept { return {bucket_ptr->_key, bucket_ptr->value()}; }
    UnorderedMapIterator& operator++() noexcept
    {
        return bucket_ptr = UnorderedMap<_Key, _Tp, _Hash, DOWNSIZE>::increment(bucket_ptr), *this;
    }
    UnorderedMapIterator operator++(int) const noexcept
    {
        return UnorderedMapIterator(UnorderedMap<_Key, _Tp, _Hash, DOWNSIZE>::increment(this->bucket_ptr));
    }
    bool operator==(const UnorderedMapIterator& itr) const noexcept { return !(*this != itr); };
    bool operator!=(const UnorderedMapIterator& itr) const noexcept { return bucket_ptr != itr.bucket_ptr; }
};
template<typename Ring>
class discrete_log
{
public:
    discrete_log(const Ring x, const ull period, const ull query) : x{x}, period{period}
    {
        for (; bs * bs * query < period; bs++) {}
        Ring y       = x ^ 0;
        const Ring z = x ^ bs;
        for (ull i = 0; i * bs < period; i++) { giant[y()] = i * bs, y *= z; }
    }
    ull operator()(Ring y)
    {
        for (ull i = 0; i < bs; i++) {
            if (giant.find(y()) != giant.end()) { return (giant[y()] + period - i) % period; }
            y = y * x;
        }
        return period;
    }

private:
    const Ring x;
    ull period;
    ull bs = 1;
    UnorderedMap<uint, ull> giant;
};
int main()
{
    using mint   = dynamic_modint<0>;
    const auto T = in<int>();
    for (int t = 0; t < T; t++) {
        const auto p = in<uint>();
        const auto k = in<uint>();
        mint::set_mod(p);
        const auto a  = in<mint>();
        const auto fs = prime_factors(p - 1);
        mint g        = 2;
        for (;; g += 1) {
            bool ok = true;
            for (const auto& f : fs) {
                const uint q = p / f.first;
                if ((g ^ q) == 1) {
                    ok = false;
                    break;
                }
            }
            if (ok) { break; }
        }
        discrete_log<mint> dlog(g, p - 1, 1);
        const ull l = dlog(a);  // y = l (mod p-1)
        if ((g ^ l) != a) {
            outln(-1);
            continue;
        }
        using pll      = std::pair<ll, ll>;
        const auto y   = crt<ll>(pll{l, p - 1}, pll{0LL, k});
        const auto z   = y.first / k;
        const auto ans = g ^ z;
        if ((ans ^ k) == a) {
            outln(ans);
        } else {
            outln(-1);
        }
    }
    return 0;
}
0