#include #include using namespace std; using namespace atcoder; struct Fast { Fast() { std::cin.tie(nullptr); ios::sync_with_stdio(false); cout << setprecision(10); } } fast; #define all(a) (a).begin(), (a).end() #define rep(i, a, b) for (int(i) = (a); (i) < (int)(b); (i)++) #define rrep(i, a, b) for (int(i) = (int)(b)-1; (i) >= (a); (i)--) using vi = vector; using ll = long long; using vl = vector; ll safe_mod(ll a, ll b) { ll c = a % b; return c < 0 ? c + b : c; } ll ext_gcd(ll a, ll b, ll& x, ll& y) { for (ll u = y = 1, v = x = 0; a;) { ll q = b / a; swap(x -= q * u, u); swap(y -= q * v, v); swap(b -= q * a, a); } return b; } const ll A_MAX = 1e9; int lg; ll k; vl powk, basis, cnt, msd; bool is_prime; ll op(ll a, ll b) { if (k == 2) return a ^ b; ll ret = 0, pow = 1; while (a | b) { ret += (a + b) % k * pow; a /= k; b /= k; pow *= k; } return ret; } ll op_pow(ll a, ll n) { if (k == 2) return n & 1 ? a : 0; if (n == 0) return 0; n = safe_mod(n, k); ll ret = 0, pow = 1; while (a) { ret += safe_mod(a % k * n, k) * pow; a /= k; pow *= k; } return ret; } void query1(ll x) { if (is_prime) { rrep(i, 0, lg) { if (x / powk[i]) { if (basis[i] == 0) { ll s, t; ext_gcd(x / powk[i], k, s, t); basis[i] = op_pow(x, s), msd[i] = 1; break; } x = op(x, op_pow(basis[i], -(x / powk[i]))); } } } else { vl a{x}; rrep(i, 0, lg) { ll g = msd[i]; vl v(a.size()), prod(a.size() + 1); rep(j, 0, a.size()) { ll u = a[j] / powk[i]; g = ext_gcd(g, u, prod[j], v[j]); prod[j] = safe_mod(prod[j], k); v[j] = safe_mod(v[j], k); } rrep(j, 1, a.size()) prod[j - 1] = safe_mod(prod[j - 1] * prod[j], k); ll t = op_pow(basis[i], prod[0]); prod[a.size()] = 1; rep(j, 0, a.size()) t = op(t, op_pow(a[j], v[j] * prod[j + 1] % k)); rep(j, 0, a.size()) a[j] = op(a[j], op_pow(t, -a[j] / powk[i] / g)); a.push_back(op(basis[i], op_pow(t, -msd[i] / g))); if (g != k) basis[i] = t, msd[i] = g; } } rep(i, 0, lg) cnt[i + 1] = cnt[i] * (k / msd[i]); } void query2(ll x) { if (x > cnt[lg]) { cout << -1 << "\n"; return; } x--; ll ans = 0; rrep(i, 0, lg) { ans = op(ans, op_pow(basis[i], x / cnt[i] - ans / powk[i] / msd[i])); x %= cnt[i]; } cout << ans << "\n"; } void query3(ll x) { x++; ll ans = 0, y = 0; rrep(i, 0, lg) { ll r = y / powk[i] % msd[i], d = x / powk[i] % k; ans += (d - r + msd[i] - 1) / msd[i] * cnt[i]; if ((d - r) % msd[i]) break; y = op(y, op_pow(basis[i], (d - y / powk[i] % k) / msd[i])); } cout << ans << "\n"; } int main() { int q; cin >> k >> q; is_prime = true; for (ll d = 2; d * d <= k; d += (d & 1) + 1) if (!(k % d)) { is_prime = false; break; } powk = vl(); for (ll p = 1; p <= A_MAX; p *= k) powk.push_back(p); lg = (int)powk.size(); basis = vl(lg, 0); msd = vl(lg, k); cnt = vl(lg + 1, 1); while (q--) { int t; ll x; cin >> t >> x; if (t == 1) query1(x); if (t == 2) query2(x); if (t == 3) query3(x); } }