import re import sys sys.setrecursionlimit(100000) def factor_integer(n): ps = [] es = [] i = 2 while (i * i <= n): e = 0 while n % i == 0: e += 1 n //= i if e > 0: ps += [i] es += [e] i += 1 if n > 1: ps += [n] es += [1] return ps, es class SegmentTree: def __init__(self, ini, op, e): self.n = len(ini) self.op = op self.e = e self.v = [e] * (2 * self.n) for i in range(self.n): self.v[self.n + i] = ini[i] for i in range(self.n - 1, 0, -1): self.v[i] = op(self.v[2 * i], self.v[2 * i + 1]) def set(self, i, x): i += self.n self.v[i] = x while i > 1: i >>= 1 self.v[i] = self.op(self.v[2 * i], self.v[2 * i + 1]) def prod(self, l, r): resl = self.e resr = self.e l += self.n r += self.n while l < r: if l & 1: resl = self.op(resl, self.v[l]) l += 1 if r & 1: resr = self.op(self.v[r - 1], resr) l >>= 1 r >>= 1 return self.op(resl, resr) def get(self, i): return self.v[i + self.n] def dump(self): print(self.v[self.n:]) content = input() pattern = r'^(\d+) (\d+) (\d+)$' result = re.match(pattern, content) if not result: sys.exit("format error.") N, B, Q = map(int, result.groups()) if not (1 <= N and N <= 10**5): sys.exit("N") if not (1 <= B and B <= 10**9): sys.exit("B") if not (1 <= Q and Q <= 10**5): sys.exit("Q") ps, es = factor_integer(B) K = len(ps) def op(x, y): res = [0] * (K + 1) for k in range(K): res[k] = x[k] + y[k] res[K] = x[K] * y[K] % B return res e = ([0] * K) + [1] content = input() pattern = '^' for n in range(N): pattern += r'(\d+)' if n < N - 1: pattern += ' ' pattern += '$' result = re.match(pattern, content) if not result: sys.exit("format error.") A = list(map(int, result.groups())) ini = [] for n in range(N): x = [0] * (K + 1) if A[n] != 0: for k in range(K): while A[n] % ps[k] == 0: A[n] //= ps[k] x[k] += 1 x[K] = A[n] % B ini += [x] seg = SegmentTree(ini, op, e) for _ in range(Q): content = input() pattern = r'^(\d+) (\d+) (\d+) (\d+)$' result = re.match(pattern, content) if not result: sys.exit("format error.") j, m, l, r = map(int, result.groups()) if not (0 <= j and j < N): sys.exit("j") if not (0 <= m and m <= 10**18): sys.exit("m") if not (0 <= l and l <= r and r < N): sys.exit("l, r") # フォーマットチェックをしたいだけなので以降の処理は放棄 if N >= 1000 or Q >= 1000: continue x = seg.get(j) divisible = False if m == B: divisible = True if x[K] != 0: for k in range(K): if x[k] < es[k]: divisible = False break if divisible: for k in range(K): x[k] -= es[k] if not divisible: if m != 0: for k in range(K): while m % ps[k] == 0: m //= ps[k] x[k] += 1 x[K] = x[K] * m % B seg.set(j, x) x = seg.prod(l, r + 1) if x[K] != 0: for k in range(K): x[K] = x[K] * pow(ps[k], x[k], B) % B print(x[K])