#include #include using namespace std; #include using BigInt = boost::multiprecision::cpp_int; pair mod_inv(int x, int m) { long long a = m, b = x % m; long long u = 0, v = 1; while (b != 0) { long long q = a / b; swap(a -= q * b, b); swap(u -= q * v, v); } if (u < 0) u += m / a; return {a, u}; } int main() { vector X{0}, Y{1}; int q; cin >> q; while (q--) { int t; cin >> t; if (t == 1) { int m, r; cin >> m >> r; if (X.back() < 0) { X.push_back(-1), Y.push_back(1); } else { auto [g, x] = mod_inv(int(Y.back() % m), m); if ((X.back() - r) % g != 0) { X.push_back(-1), Y.push_back(1); } else { long long y = int((r - X.back()) % m); if (y < 0) y += m; m /= g; X.push_back(X.back() + Y.back() * (y / g * x % m)); Y.push_back(Y.back() * m); } } } else if (t == 2) { int k; cin >> k; while (k--) X.pop_back(), Y.pop_back(); } else { int m; cin >> m; cout << (X.back() < 0 ? -1 : (int)(X.back() % m)) << "\n"; } } }