#include #include #include #include #include using namespace std; using ll = long long; using vi = vector; using v2i = vector; using t4i = tuple; constexpr int X = 1e9; t4i exgcd(int a, int b) { if (b == 0) { return {1, 0, 0, 1}; } auto [k1, k2, k3, k4] = exgcd(b, a % b); return {k2, k1 - a / b * k2, k4, k3 - a / b * k4}; } int main() { int k, q; cin >> k >> q; int n = log(X) / log(k) + 1; v2i base(n); while (q--) { int op; ll x; cin >> op >> x; if (op == 1) { int xd[n]; for (int i = 0; i < n; i++) { xd[i] = x % k; x /= k; } for (int i = n - 1; i >= 0; i--) { if (xd[i] == 0) { continue; } auto [k1, k2, k3, k4] = exgcd(xd[i], base[i].empty() ? k : base[i][i]); if (base[i].empty()) { base[i] = vi(n); } int t[n]; copy(base[i].begin(), base[i].end(), t); for (int j = 0; j < n; j++) { base[i][j] = ((1ll * k1 * xd[j] + 1ll * k2 * t[j]) % k + k) % k; } for (int j = 0; j < n; j++) { xd[j] = ((1ll * k3 * xd[j] + 1ll * k4 * t[j]) % k + k) % k; } } } else if (op == 2) { x--; int xd[n]; for (int i = 0; i < n; i++) { if (!base[i].empty()) { xd[i] = x % (k / base[i][i]); x /= k / base[i][i]; } } if (x > 0) { cout << -1 << endl; continue; } int ans[n]; fill(ans, ans + n, 0); for (int i = n - 1; i >= 0; i--) { if (!base[i].empty()) { int t = ((xd[i] - ans[i] / base[i][i]) % k + k) % k; for (int j = 0; j < n; j++) { ans[j] = (ans[j] + 1ll * t * base[i][j]) % k; } } } ll t = 0; for (int i = n - 1; i >= 0; i--) { t = t * k + ans[i]; } cout << t << endl; } else { int xd[n]; for (int i = 0; i < n; i++) { xd[i] = x % k; x /= k; } if (x > 0) { xd[n-1] = k; } int r[n]; fill(r, r + n, 0); ll dp[n+1][2]; fill(dp[0], dp[n+1], 0); dp[n][1] = 1; for (int i = n - 1; i >= 0; i--) { int t = base[i].empty() ? k : base[i][i]; dp[i][0] = dp[i+1][0] * (k / t); dp[i][0] += dp[i+1][1] * (xd[i] / t + (r[i] % t < xd[i] % t)); if (xd[i] < k && r[i] % t == xd[i] % t) { dp[i][1] = dp[i+1][1]; if (!base[i].empty()) { int k1 = ((xd[i] - r[i]) / t + k) % k; for (int j = 0; j < n; j++) { r[j] = (r[j] + 1ll * k1 * base[i][j]) % k; } } } } cout << dp[0][0] + dp[0][1] << endl; } } return 0; }