#include using namespace std; #if __has_include() #include using namespace atcoder; using mint = modint998244353; // using mint = modint1000000007; // using mint = double; #endif //define using ll = long long; using ull = unsigned long long; using pii = pair; using pll = pair; using vi = vector; using vll = vector; #define rep(i,l,r) for (int i = (int)(l); i < (int)(r); i++) #define rrep(i,l,r) for (int i = (int)(r-1); i >= (int)(l); i--) #define len(x) (int)(x).size() #define all(x) (x).begin(), (x).end() #define elif else if #define pb push_back #define eb emplace_back #define fi first #define se second const int inf = 1e9; const long long infl = 1LL<<60; const int mod = 998244353; ll pow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; } template bool chmin(T& a, const U& b){ if(a > T(b)){ a = b; return 1; } return 0; } template bool chmax(T& a, const U& b){ if(a < T(b)){ a = b; return 1; } return 0; } template using spq = priority_queue, greater>; templateistream& operator>>(istream& i, vector& v) {for(int j = 0; j < (int)(v).size(); j++) i >> v[j]; return i;} struct IoSetup { IoSetup() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); cerr << fixed << setprecision(15); } } iosetup; #include using namespace std; using namespace boost::multiprecision; using Int = cpp_int; Int extgcd(Int a, Int b, Int &x, Int &y) { if (b == 0) { x = 1; y = 0; return a; } Int d = extgcd(b, a % b, y, x); y -= (a / b) * x; return d; } pair crt(Int r1, Int m1, Int r2, Int m2) { Int p, q; Int g = extgcd(m1, m2, p, q); if ((r2 - r1) % g != 0) { return {0, 0}; } Int lcm = (m1 / g) * m2; Int m2_div_g = m2 / g; Int tmp = (r2 - r1) / g; Int k = (tmp * p) % m2_div_g; Int r = (r1 + m1 * k) % lcm; if (r < 0) r += lcm; return {r, lcm}; } int main() { int Q; cin >> Q; vector M(Q + 5, 1); vector R(Q + 5, 0); M[0] = 1; R[0] = 0; int idx = 1; for (int i = 0; i < Q; ++i) { int t; cin >> t; if (t == 1) { ll m, r; cin >> m >> r; if (M[idx - 1] != 0) { pair res = crt(R[idx - 1], M[idx - 1], r, m); R[idx] = res.first; M[idx] = res.second; } else { M[idx] = 0; } idx++; } else if (t == 2) { int k; cin >> k; idx -= k; } else { ll m; cin >> m; if (M[idx - 1] != 0) { cout << (R[idx - 1] % m) << "\n"; } else { cout << "-1\n"; } } } return 0; }