## 1) Abridged problem statement

For each test case, given integers \(n\) (\(3 \le n \le 10^6\)) and a prime \(p\) (\(2 \le p \le 10^6\)), find nonzero residues \(x,y,z \in \{1,\dots,p-1\}\) such that
\[
x^n + y^n \equiv z^n \pmod p,
\]
or output `-1` if no such triple exists. Any valid triple is accepted.

---

## 2) Detailed editorial (solution idea)

### Key group facts

Because \(p\) is prime, the nonzero residues modulo \(p\) form a multiplicative cyclic group:
\[
(\mathbb{Z}/p\mathbb{Z})^\* \quad \text{has size } \varphi(p)=p-1.
\]
So there exists a **primitive root** \(r\) such that every nonzero element can be written as \(r^k\) for some \(k\in[0,p-2]\).

Consider the map
\[
f(x) = x^n \pmod p.
\]
In exponent form, if \(x=r^k\), then
\[
x^n \equiv (r^k)^n = r^{kn} \pmod p.
\]
So the set of all \(n\)-th powers is the set of exponents reachable as multiples of \(n\) modulo \(p-1\). Let
\[
g = \gcd(n, p-1).
\]
Then the set of multiples of \(n\) modulo \(p-1\) is exactly the set of residues divisible by \(g\). Therefore:

- The set of \(n\)-th powers is the subgroup
  \[
  H = \{ r^{g\cdot t} : t=0,1,\dots,\tfrac{p-1}{g}-1 \},
  \]
- It has size \(|H| = \frac{p-1}{g}\),
- It is generated by \(r^g\).

So we can enumerate all \(n\)-th power values by walking powers of \(r^g\).

### Reducing to \(z=1\)

We need \(x^n + y^n \equiv z^n\). If we can find a solution with \(z=1\), we’re done:
\[
x^n + y^n \equiv 1 \pmod p.
\]
Why is that enough? If we had any solution \(a+b\equiv c\) with \(a,b,c\in H\), then multiplying by \(c^{-1}\) (exists since \(c\neq 0\)) gives:
\[
a c^{-1} + b c^{-1} \equiv 1.
\]
But the implemented solution takes the even simpler route: directly searches for \(a,b\in H\) such that \(a+b\equiv 1\).

Once we find \(a=x^n\) and \(b=y^n\) with \(a+b\equiv 1\), we output \((x,y,1)\) and it satisfies the requirement (since \(1^n\equiv 1\)).

### Finding \(a,b\in H\) with \(a+b\equiv 1\)

Enumerate the subgroup:
- Let \(rt = r^g \bmod p\).
- Start from \(1\) and repeatedly multiply by \(rt\) to get all subgroup elements:
  \[
  cur = rt^1, rt^2, \dots
  \]
Store each seen value in an array/dictionary `seen[value]=index`.

For each `cur`, compute:
\[
other \equiv 1-cur \pmod p.
\]
If `other` has already been seen, we have:
\[
cur + other \equiv 1 \pmod p,
\]
and both are in \(H\), so each is an \(n\)-th power.

If we return to `cur == 1` after completing the whole cycle without a match, then **no such pair exists**, hence no solution of this form exists, and the code outputs `-1`.

### Recovering \(x\) from \(x^n = r^{gk}\) (taking an \(n\)-th root)

Suppose we found that
\[
x^n \equiv r^{gk} \pmod p
\]
for some integer \(k\) (the step count in the subgroup enumeration). We want \(x=r^e\) such that:
\[
(r^e)^n = r^{en} \equiv r^{gk} \pmod p
\]
which means, in exponents modulo \(p-1\):
\[
en \equiv gk \pmod{p-1}.
\]
Divide by \(g\):
\[
e\cdot (n/g) \equiv k \pmod{(p-1)/g}.
\]
Now \(\gcd(n/g,(p-1)/g)=1\), so \((n/g)\) has a modular inverse modulo \((p-1)/g\). Thus:
\[
e \equiv k \cdot (n/g)^{-1} \pmod{(p-1)/g}.
\]
Then \(x = r^e \bmod p\).

The solution computes this inverse with extended Euclid and then modular exponentiation.

### Primitive root finding

To generate \(H\) we need a primitive root \(r\). The code finds one by:
1. Let \(\phi=p-1\).
2. Enumerate all divisors \(d\) of \(\phi\).
3. A candidate \(r\) is primitive iff for every **proper divisor** \(d<\phi\), \(r^d \not\equiv 1 \pmod p\).
4. The code tries \(r=2,3,\dots\) until it finds a valid one.

For \(p\le 10^6\) this is fast enough in practice.

### Complexity

Per test case:
- Primitive root search: roughly \(O(\sqrt{p}\log p)\) (divisors + pow checks, small constants).
- Subgroup scan: \(O(|H|)\) multiplications and O(1) checks, where \(|H|=(p-1)/g\).
- Each modular power: \(O(\log p)\).

So total is essentially \(O\left(\frac{p-1}{g} + \sqrt{p}\right)\) per test, good under constraints.

---

## 3) The provided C++ solution with detailed line-by-line comments

```cpp
#include <bits/stdc++.h>
using namespace std;

// Pretty-print a pair as "first second"
template<typename T1, typename T2>
ostream& operator<<(ostream& out, const pair<T1, T2>& x) {
    return out << x.first << ' ' << x.second;
}

// Read a pair from input
template<typename T1, typename T2>
istream& operator>>(istream& in, pair<T1, T2>& x) {
    return in >> x.first >> x.second;
}

// Read a vector: read each element in order
template<typename T>
istream& operator>>(istream& in, vector<T>& a) {
    for (auto& x : a) {
        in >> x;
    }
    return in;
};

// Print a vector with spaces after each element
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& a) {
    for (auto x : a) {
        out << x << ' ';
    }
    return out;
};

int n, p;

// Read one test case: n and prime p
void read() { cin >> n >> p; }

// Fast modular exponentiation: compute a^e mod m in O(log e)
int64_t modpow(int64_t a, int64_t e, int64_t m) {
    int64_t r = 1;                 // accumulator for result
    for (; e; e >>= 1) {           // while exponent > 0, process bits
        if (e & 1) {               // if current bit is set
            r = r * a % m;         // multiply into result
        }
        a = a * a % m;             // square base each step
    }
    return r;
}

// Find a primitive root modulo prime p (generator of multiplicative group)
int primitive_root(int p) {
    vector<int> divs;
    int phi = p - 1;               // group size

    // Collect all divisors of phi
    for (int i = 1; (int64_t)i * i <= phi; i++) {
        if (phi % i == 0) {
            divs.push_back(i);
            if (i * i < phi) {
                divs.push_back(phi / i);
            }
        }
    }
    sort(divs.begin(), divs.end()); // sort divisors ascending

    // Try candidates g = 2..p-1
    for (int g = 2; g < p; g++) {
        bool ok = true;

        // For primitive root: for all proper divisors d < phi,
        // we must have g^d != 1 (mod p).
        // divs includes 1 and phi; by iterating until size-1 we skip phi.
        for (int i = 0; i + 1 < (int)divs.size() && ok; i++) {
            if (modpow(g, divs[i], p) == 1) {
                ok = false;        // order divides divs[i], not primitive
            }
        }
        if (ok) {
            return g;              // found generator
        }
    }
    return -1;                     // should not happen for prime p
}

// Modular inverse of a modulo m, assuming gcd(a,m)=1.
// Implemented via iterative extended Euclid.
int64_t mod_inverse(int64_t a, int64_t m) {
    int64_t g = m, x = 0, y = 1;   // (g,x) tracks coefficients for current g
    for (int64_t r = a; r != 0;) { // r is current remainder
        int64_t q = g / r;         // quotient
        g -= q * r;                // g becomes g % r
        swap(g, r);                // rotate (g,r) like Euclid
        x -= q * y;                // update coefficient
        swap(x, y);                // rotate coefficients
    }
    // At end, g = gcd(a,m)=1 and x is inverse possibly negative; normalize
    return (x % m + m) % m;
}

// Recover an n-th root:
// We know target is rt^(g*k) and want x such that x^n = rt^(g*k).
// n_div_g = n/g, phi_div_g = (p-1)/g, and rt is primitive root.
int nth_root(int k, int rt, int g, int n_div_g, int phi_div_g, int p) {
    // Solve exponent equation:
    // x = rt^e, so x^n = rt^(e*n) = rt^(g*k) mod p.
    // => e*(n/g) = k (mod (p-1)/g).
    // => e = k * inv(n/g) (mod (p-1)/g).
    int64_t e = mod_inverse(n_div_g, phi_div_g) * k % (p - 1);
    return modpow(rt, e, p);       // return rt^e mod p
}

void solve() {
    // g = gcd(n, p-1) determines subgroup of n-th powers
    int g = gcd(n, p - 1);

    // rt is primitive root (generator) of multiplicative group mod p
    int rt = primitive_root(p);

    // rt_g generates subgroup of n-th powers: (rt^g)^t
    int rt_g = modpow(rt, g, p);

    // seen[v] = step index when v was reached, or -1 if not in table yet
    vector<int> seen(p, -1);

    int64_t cur = 1;   // current subgroup element (start at 1)
    int cnt = 0;       // counts steps: cur = (rt_g)^cnt

    while (true) {
        // Advance one step in subgroup
        cur = cur * rt_g % p;

        // Record when we saw cur
        seen[cur] = ++cnt;

        // If we returned to 1, we completed the whole subgroup cycle
        // without finding a pair summing to 1 => no solution of desired form.
        if (cur == 1) {
            cout << -1 << "\n";
            return;
        }

        // Compute other = 1 - cur mod p
        int other = (1 - cur % p + p) % p;

        // If other already seen, then cur + other == 1 (mod p)
        // and both are in subgroup of n-th powers.
        if (seen[other] != -1) {
            // cur = (rt^g)^cnt = rt^(g*cnt) = x^n for some x
            int x = nth_root(cnt, rt, g, n / g, (p - 1) / g, p);

            // other = (rt^g)^(seen[other]) = rt^(g*seen[other]) = y^n
            int y = nth_root(seen[other], rt, g, n / g, (p - 1) / g, p);

            // z = 1 works since 1^n = 1
            cout << x << " " << y << " " << 1 << "\n";
            return;
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T = 1;
    cin >> T;
    for (int test = 1; test <= T; test++) {
        read();
        solve();
    }
    return 0;
}
```

---

## 4) Python solution (same approach) with detailed comments

```python
import sys
from math import gcd, isqrt

# Fast modular exponentiation: a^e mod m
def modpow(a: int, e: int, m: int) -> int:
    r = 1
    a %= m
    while e > 0:
        if e & 1:
            r = (r * a) % m
        a = (a * a) % m
        e >>= 1
    return r

# Extended Euclid for modular inverse (a^{-1} mod m), assuming gcd(a,m)=1
def modinv(a: int, m: int) -> int:
    # Iterative extended-gcd style similar to the C++ code
    g, x, y = m, 0, 1
    r = a
    while r != 0:
        q = g // r
        g, r = r, g - q * r
        x, y = y, x - q * y
    # x is inverse (maybe negative)
    return x % m

# Find a primitive root modulo prime p
def primitive_root(p: int) -> int:
    phi = p - 1

    # Collect all divisors of phi
    divs = []
    for i in range(1, isqrt(phi) + 1):
        if phi % i == 0:
            divs.append(i)
            if i * i != phi:
                divs.append(phi // i)
    divs.sort()

    # Try candidates 2..p-1
    for g in range(2, p):
        ok = True
        # Check all proper divisors d < phi (skip the last which is phi itself)
        for d in divs[:-1]:
            if modpow(g, d, p) == 1:
                ok = False
                break
        if ok:
            return g
    return -1  # should not happen for prime p

# Compute x such that x^n = rt^(g*k) (mod p), where rt is primitive root
def nth_root(k: int, rt: int, g: int, n_div_g: int, phi_div_g: int, p: int) -> int:
    # Solve e*(n/g) = k (mod (p-1)/g)
    inv = modinv(n_div_g, phi_div_g)
    e = (inv * k) % (p - 1)   # safe to reduce mod (p-1)
    return modpow(rt, e, p)

def solve_case(n: int, p: int) -> str:
    g = gcd(n, p - 1)
    rt = primitive_root(p)
    rt_g = modpow(rt, g, p)  # generator of subgroup of n-th powers

    # seen[value] = step index in subgroup enumeration, -1 means not seen
    seen = [-1] * p

    cur = 1
    cnt = 0

    while True:
        # Move to next element in subgroup: cur = (rt_g)^cnt
        cur = (cur * rt_g) % p
        cnt += 1
        seen[cur] = cnt

        # Completed the cycle => no pair found
        if cur == 1:
            return "-1"

        # Want another subgroup element 'other' such that cur + other == 1 (mod p)
        other = (1 - cur) % p

        if seen[other] != -1:
            x = nth_root(cnt, rt, g, n // g, (p - 1) // g, p)
            y = nth_root(seen[other], rt, g, n // g, (p - 1) // g, p)
            return f"{x} {y} 1"

def main():
    data = sys.stdin.read().strip().split()
    t = int(data[0])
    out = []
    idx = 1
    for _ in range(t):
        n = int(data[idx]); p = int(data[idx + 1]); idx += 2
        out.append(solve_case(n, p))
    sys.stdout.write("\n".join(out))

if __name__ == "__main__":
    main()
```

---

## 5) Compressed editorial

- Work in \((\mathbb{Z}/p\mathbb{Z})^\*\) (cyclic of size \(p-1\)). Let \(r\) be a primitive root.
- The set of \(n\)-th powers is a subgroup \(H=\langle r^g\rangle\) where \(g=\gcd(n,p-1)\). Size \(|H|=(p-1)/g\).
- Search for \(a,b\in H\) with \(a+b\equiv 1\pmod p\): enumerate \(cur=(r^g)^t\), store in `seen`, and check whether \(1-cur\) was seen.
- If found at steps \(t_1,t_2\), then \(cur=r^{g t_1}=x^n\), \(other=r^{g t_2}=y^n\). Recover roots by solving
  \(e(n/g)\equiv t \pmod{(p-1)/g}\) so \(e=t\cdot (n/g)^{-1}\).
  Output \((r^e, r^{e'}, 1)\).
- If enumeration returns to 1 with no match, output `-1`.