We need to handle range multiply and range query for totient of product. Constraints: n up to 4e5, q up to 2e5, a_i and x up to 300. Need to answer φ(∏_{i=l}^{r} a_i) mod 1e9+7.
Let P = ∏ a_i over range. Then φ(P) = P * ∏_{p|P} (1 - 1/p). So we need product of values and also which primes divide the product. Since numbers are small (≤300), primes up to 300 are only a few. Let's list primes ≤300: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293. That's 62? Actually count: π(300) = 62? Let's compute: π(300) = 61? Let's quickly list: up to 300: primes: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293. That's 62? Let's count: from 2 (1) ... 293 (maybe 62). Actually known: π(300)=62. Yes, there are 62 primes ≤ 300. So we have at most 62 distinct prime factors.
Thus we can maintain for each prime p, whether it divides the product over a range. Actually we need product over primes that divide the product: ∏{p|P} (1 - 1/p). That's equivalent to ∏{p} (1 - 1/p)^{[p divides P]}. Since exponent either 0 or 1? Wait, if a prime appears multiple times, does it affect? For Euler's totient, φ(n) = n ∏_{p|n} (1 - 1/p). The product is over distinct primes dividing n. So we only care if prime divides the product at least once. So we need to know for each prime, whether the product over the range has that prime as a factor (i.e., at least one a_i in the range is divisible by p). So we need to maintain for each prime a boolean: does the range contain at least one multiple of p? But note: after multiplication by x, we multiply a_i by x, so new a_i may become divisible by more primes. So we need to track the prime factors of each element and updates.
Because x is up to 300, we can factorize numbers into prime factors (distinct primes). For each element a_i, we can maintain a bitset of primes that divide it. But we also need product modulo mod? For φ(P) we need product of all a_i modulo mod, times the product over primes of (1 - inv(p)) if that prime appears in the range. So we need two things:
- Range product of values (mod MOD).
- For each prime p (62), a boolean (or count) indicating whether any element in range has p as a factor.
We need to support range multiplication: multiply a segment by x. This changes both product and prime presence.
Simplify: Since multiplication is multiplicative, we can treat the array as product of initial values times cumulative multipliers applied to each element. But careful: multiplication by x is applied to each element individually. So each a_i gets multiplied by various x's over time. Since q up to 2e5, we need a data structure that can handle range multiply and range query (product and prime presence). The numbers can become large (up to initial ≤300, multiply by up to 300 many times). But we only need modulo for product and need distinct prime factors of the overall product. However, the product may have large exponents, but totient formula still uses distinct primes. So we need to know for each prime p, whether the product of the range contains p (i.e., at least one factor p). That is equivalent to: whether any a_i in the range, after all updates, has p in its factorization. So if an element's value is multiplied by x, its set of prime divisors becomes the union of its current set and prime divisors of x. So each element's prime set only expands; it never loses primes. So the presence of a prime in the range is monotonic: once a prime appears in an element, it stays. That's important! Because multiplication by x only adds prime factors. So we can treat each prime's presence across the array as a boolean that flips from 0 to 1 only. Range multiply query adds prime factors to all elements in a range. That's like range activation (set to 1) for each prime that divides x. And we need to query, for each prime, whether any element in range is active. This is essentially a range OR query? Actually we need to know if any element in range has that prime. If we maintain per prime a segment tree that stores whether that prime is present in the segment (i.e., OR of booleans). Then a range multiply by x means for each prime p dividing x, we need to set that prime's presence in the range to 1. But careful: it's not setting to 1 for each element; we need to ensure that for each element in the range, after multiplication by x, its prime set includes p. Since the prime presence for that element becomes 1 if it wasn't already. And the segment tree for prime p stores whether any element in a segment has p. If we set all elements in the range to have p, then the OR over that segment becomes 1. But we need to update the data structure to reflect that. However, if the segment already had some 1s, it's still 1. To support this, we could use lazy propagation that sets the range to 1 (or OR with 1). Since it's monotonic (only 0->1), we can use a segment tree with lazy "set to 1" for each prime. But there are 62 primes; building 62 segment trees would be heavy: 62 * O(n) nodes => 624e5 ~ 24.8e6, which is maybe okay (24 million). Each node stores a boolean (or maybe char). But query for totient: we need to know for each prime if any in range, so we need to OR across primes? Actually we need to combine: for each prime, we query whether it's present in the range. Then we compute product over primes: if present, multiply by (1 - inv(p)). So we need to query all primes. That would be 62 separate queries per totient query, which is 62 * log n * q ~ 62 * log(4e5) * 2e5 ~ 62 * 19 * 2e5 ≈ 235.6 million operations, maybe borderline but possibly okay in C++ with optimization (since 2e5 * 19 = 3.8e6 per prime? Actually 622e5 = 12.4e6, times log n 19 = 235.6e6. That might be okay if each operation is simple (bit operations). But we also have range multiply updates: each multiply updates for each prime divisor of x. x <=300, so at most 5 distinct primes? Actually 300=2^235^2 => distinct primes: 2,3,5. So at most about 5 distinct primes. So each MULTIPLY query would need to update each of those primes' segment trees over a range (set to 1). That's at most 5 * log n updates per multiply. That's okay.
But we also need to maintain product of values mod MOD. For product, we need to support range multiply by x: multiply each element by x. That's a typical range multiplication update with lazy propagation, and we also need range product query. Since MOD is prime (1e9+7). That's doable with a segment tree.
Thus overall we could have:
-
Segment tree for product: each node stores product of its segment modulo MOD, and lazy multiplier (default 1) representing factor to multiply the whole segment. Range multiply: update node with multiplying value^len? Actually we need to multiply each element by x, so the product of the segment gets multiplied by x^{len}. So we can store lazy as a multiplier (like x) that we propagate, and apply by multiplying node value by pow(x, len). But careful: multiple multiplications: we can combine lazily by multiplying the lazy factor (mod MOD). For product query we need to return product over range.
-
For primes: 62 separate segment trees or better: we can combine them into a single segment tree storing a 64-bit bitset (or maybe 62 bits) indicating which primes are present in the segment (i.e., OR of bits of elements). Then an update "multiply range by x" would need to set the bits corresponding to primes dividing x to 1 for all elements in that range. That is like performing a bitwise OR with mask (bits for those primes) over the range. But careful: if we store bitset per node representing whether any element in the segment has that prime, then when we set a range to have certain primes (by setting each element's bits), the effect on the OR of the segment is: the segment's bits become OR of the mask (since every element will eventually have those bits). Actually if we set each element in the range to have those primes, then the OR of the segment will have those bits set. However, if we lazily set the range to have mask, we need to know if the range is fully covered: we can set the node's bits to (bits |= mask) because every element now definitely has those bits? Wait, careful: The bitset stored at a node indicates whether there exists at least one element in the segment with that prime. If we apply an operation that forces every element in the segment to have those primes, then after the operation, for each prime in mask, there will be at least one element (in fact all) having that prime, so the bit should become 1. But for primes not in mask, existing bits remain unchanged. So the new bits become old_bits OR mask. That's the effect. Also, if we have lazy propagation, we need to store a lazy mask that still needs to be applied to children, representing that each element in the segment should have these primes turned on. Since the operation is "OR with mask" for each element's prime set, we can combine lazy masks as OR as well. Because applying multiple masks: OR of masks. And when pushing down, we just OR child's lazy and child's node bits with the mask.
But is it sufficient to just store OR of bits? For the query, we need to know the OR of the bits over the range, i.e., which primes appear at least once. That's exactly what the node's bitset gives. And updates are monotonic: only adding bits. So we can have a segment tree with each node storing a bitset (64-bit integer, 62 bits) of primes present in that segment, and a lazy mask (64-bit) of bits that need to be ORed to all elements in the subtree. Because the operation is "set these bits on all elements" (i.e., OR each element's bits with mask). Since it's OR, we can combine lazily.
However, there is a nuance: The OR for a node after applying mask to its whole segment should be node.bits OR mask (since every element gets those bits). That's correct. But what about propagation? Suppose we have a node with current bits, and we receive a mask to OR to all elements. We update node.bits |= mask, and we OR mask into node.lazy (node.lazy |= mask). Then when pushing to children, we apply the same mask to children. That's typical lazy propagation for range bitwise OR updates and query for OR over range? But here we are OR-ing each element's bitmask; then the OR over the segment is just OR of all element masks. Since the operation is to set bits for each element, the OR over segment after operation is old OR OR mask. So yes.
Thus we can have a segment tree over n elements, each leaf i stores a bitset (64-bit) representing the primes that divide a_i (initial). Then we also maintain product tree separately.
Now for MULTIPLY l r x:
- Update product segment tree: range multiply by x.
- Update prime bitset segment tree: compute mask = bitset of primes dividing x. Then apply range OR with mask.
For TOTIENT l r:
- product = query_product(l, r)
- mask = query_or_bits(l, r) (i.e., bitset of primes present in range)
- For each prime p where the bit is set, multiply product by (1 - inv(p)) mod MOD. Alternatively, precompute factor = ∏_{p} (1 - p^{-1}) for all primes? But we need only those present, so we multiply by product of (1 - inv(p)) for p in mask.
- Answer = product * ∏_{p in mask} (1 - inv(p)) mod MOD.
We need modular inverse of p mod MOD. Since MOD is prime and p<MOD, inv(p) exists.
Edge Cases: The product might be 0? a_i >=1, so product never 0 mod MOD. MOD ~1e9+7, product fits.
But wait: In totient formula, φ(P) = P * ∏_{p|P} (1 - 1/p). But if P is large, we take modulo. However, note that P * ∏(1-1/p) is integer. But if we compute P mod MOD and multiply by ∏(1-inv(p)) mod MOD, we get φ(P) mod MOD? Since the expression is rational but result integer. Taking modulo we have to ensure we multiply by modular inverses appropriately. Indeed we compute product_mod = ∏ a_i mod MOD. Then for each p, multiply by (1 - inv(p)) mod MOD. That yields (∏ a_i) * ∏ (1 - p^{-1}) mod MOD. But is that equal to φ(∏ a_i) mod MOD? Note that ∏ a_i may have factors of p that cancel denominators. Since (1 - 1/p) = (p-1)/p, the product becomes (∏ a_i) * ∏ (p-1)/p. Since ∏ a_i includes p factors, the denominators can cancel. However, when we compute modularly, we are effectively computing (∏ a_i mod MOD) * ∏ ((p-1) * inv(p) mod MOD). That's not necessarily equal to φ(∏ a_i) mod MOD because the integer φ(∏ a_i) is (∏ a_i) * ∏ (1-1/p), but the cancellation of denominators is exact integer. However, computing it as product_mod * ∏ ((p-1)*inv(p)) mod MOD is actually correct as a modular evaluation, because:
Let N = ∏ a_i. Let S be set of distinct primes dividing N. Then φ(N) = N * ∏{p∈S} (1 - 1/p) = N * ∏{p∈S} (p-1)/p = (∏{p∈S} p^{-1}) * N * ∏{p∈S} (p-1). But N contains each p to some exponent ≥1, so N includes factor ∏{p∈S} p^{e_p}. Thus φ(N) = (∏{p∈S} p^{e_p-1}) * ∏_{p∈S} (p-1). But that's integer.
Now compute M = (∏ a_i mod MOD) * ∏{p∈S} ((p-1) * inv(p) mod MOD). Let’s denote A = ∏ a_i (integer). Then M ≡ A * ∏ (p-1) * inv(p) (mod MOD). Since A = ∏ p^{e_p} * other primes? Actually A includes all primes. Write A = (∏{p∈S} p^{e_p}) * B where B is product of primes not in S (or other factors). But anyway, the product A * ∏ inv(p) = (∏{p∈S} p^{e_p} * B) * ∏ inv(p) = B * ∏{p∈S} p^{e_p - 1}. So M ≡ B * ∏{p∈S} p^{e_p - 1} * ∏{p∈S} (p-1) (mod MOD). That's exactly φ(N) mod MOD, because φ(N) = B * ∏_{p∈S} p^{e_p - 1} * (p-1). So yes, M ≡ φ(N) mod MOD. So it's correct to compute product_mod * ∏ ((p-1)*inv(p)) mod MOD, as long as we consider distinct primes S. Good.
Thus we can compute ans = prod_mod * ∏_{p where mask bit set} ((p-1)*inv(p) % MOD) mod MOD.
We need precomputation for each prime p: factor[p] = (p-1) * inv(p) % MOD. Actually we could precompute (1 - inv(p)) mod MOD.
But note: product_mod might be huge but we keep mod.
Now complexity: Building product segment tree O(n). Building prime bitset segment tree O(n) with 64-bit masks.
Query: For totient, we need to get product and mask. product query: O(log n). mask query: also O(log n) retrieving combined OR of bitsets. Actually we can query the OR over range in segment tree: combine masks via bitwise OR. That returns a 64-bit mask for the whole range. So we only need one mask query O(log n). Then we need to iterate over bits set in mask. There are at most 62 bits, so per totient query we may iterate up to 62 bits. But we can precompute an array mul_factor[prime_index] = (1 - inv(p)) mod MOD, and also store maybe a product over all bits? But we need only those present. So we can precompute for each prime its factor. Then in query, iterate over bits set: for each set bit, multiply ans by factor[bit_index]. But we can also precompute the product for all possible masks? There are 2^62 possibilities, not feasible. So iteration over set bits is fine: each totient query may have up to 62 iterations, worst-case all primes appear. However, note that the numbers a_i and x are ≤300, so only primes ≤300 can appear. That's exactly 62. But can all 62 appear simultaneously? Possibly yes, if the product includes many different primes across the range. In worst case, each element might contain distinct primes, but since each number ≤300 can have at most maybe 5 distinct primes (max distinct primes in numbers ≤300? 235711=2310 >300, so at most 4? Actually 2357=210, 235711=2310>300 so max distinct primes for a number ≤300 is 4? 235711 is too high. 2357=210; 235713? that's 2730. So maximum distinct prime factors for numbers ≤300 is 4. Actually 300=2^235^2 -> 3 distinct. 210=2357 ->4 distinct. 330 >300. So yes, each element has at most 4 distinct primes. But across a range of up to 4e5, the union of distinct primes could be up to all 62. So it's possible for a large range that all primes appear. So worst-case per totient query could be 62 multiplications. With q up to 2e5 and at least one totient query, worst-case if many totient queries (e.g., half) then 2e562 ≈ 12.4 million multiplications, which is fine. Actually 2e562 = 12.4e6, not 12.4 million? 200,00062 = 12,400,000. That's 12.4 million, definitely fine. The product query and mask query each O(log n) ~ 19 steps, also fine.
Now updates: MULTIPLY: we need to update product tree: O(log n). And update prime bitset tree: we compute mask for x (distinct primes), then do range OR with mask: O(log n) for updating mask tree. Since mask is a 64-bit integer, combining is cheap.
Thus overall complexity: O((n+q) log n) with small constants.
Memory: segment tree for product: 4n nodes storing mod value, and lazy multiplier (mod). For prime bitset: 4n nodes storing uint64_t bits and uint64_t lazy mask. That's about 4*4e5=1.6M nodes per tree, two trees ~3.2M nodes. Each node in bitset tree: two 64-bit integers -> 16 bytes. So ~25.6 MB. Product tree: each node stores val (8 bytes), lazy (8 bytes) -> 16 bytes, so ~25.6 MB. Total ~51.2 MB, fine.
But we need to be careful: Lazy for product tree: we need to store multiplicative lazy tag, initially 1. For range multiply by x, we need to update node val = val * pow(x, len) % MOD, and lazy = lazy * x % MOD. But careful: For lazy propagation, if we have multiple pending multiplications, we combine by multiplying. However, when we apply a multiplication to a segment, we need to multiply the node's product by x^{len}. So we need fast exponentiation? Since x <= 300 and len can be up to n, we could precompute powers of each x for all possible lengths? Not possible. But we can compute pow_mod(x, len, MOD) using fast exponentiation O(log len). But that would be too heavy per update. Alternative: Use segment tree with lazy multiplication that stores the factor to apply to the whole segment. The product of the segment can be updated by multiplying by factor^len? Actually we can apply update as: node.val = node.val * (x^{len}) mod MOD. We can compute x^len % MOD by fast exponentiation, but len could be large but exponentiation O(log len) is okay because len up to n=4e5, log2 ~19. So each node update would require exponentiation. However, we have O(log n) nodes per update, each requiring exponentiation O(log len) ~ O(log n), leading to O(log^2 n) per update. That's acceptable? 2e5 * (log^2) ~ 2e5 * 400? Actually log n ~19, log len ~19 => 361 operations per update; total ~72 million modular multiplications, may be okay but we can do better by precomputing powers of all possible x? x only up to 300, and len can vary. We could precompute for each x (1..300) an array of powers up to n? That's 300 * 4e5 = 120 million integers, too large. Alternatively, we can treat the segment tree differently: store product, and lazy as multiplier. When we need to apply a multiplication factor to a node covering length L, we can compute node.val = node.val * (x^L) % MOD. To compute x^L quickly, we can precompute for each x (1..300) powers of x in exponents that are powers of two? Or we can use fast exponentiation per node as needed; it's probably okay given constraints. But we also need to consider updates in product tree: there may be many MULTIPLY queries, up to 2e5. Each update touches O(log n) nodes, each node requires exponentiation of x to its segment length. So worst-case operations: 2e5 * 19 * 19 = 72.2e6 exponentiations? Actually each exponentiation does about log(L) multiplications, but we can compute pow_mod once per node. However, we can optimize: Since we know the length of each node is fixed (segment length). So we could precompute for each node its length, and also maybe precompute for each x the value x^len for each node? That would be 300 * 1.6M = 480M entries, impossible. Another approach: Use a Fenwick tree with range multiplication? But Fenwick typically supports point updates, range queries. We need range multiply and range product query; segment tree with lazy is typical.
Alternatively, we could avoid exponentiation by using multiplicative lazy that stores factor and we update node.val by multiplying by factor^len. But we could also store node.val as product of a_i * cumulative multiplier^len? Wait, there is a trick: Since multiplication is commutative, we can store at each node the product of original values times multiplier^len? Actually if we have lazy multiplier m (applied to whole segment), the product of the segment should be (original_product) * m^{len}. But we don't know original_product separate? We can maintain that node.val always reflects the correct product including all applied lazy. So when we apply a new multiplier x to a node with current lazy tag old_lazy, we can combine: new_lazy = old_lazy * x % MOD. And node.val = node.val * (x^{len}) % MOD. That's exactly.
To compute x^{len} efficiently, we could precompute powers of all x for all possible lengths? Not feasible. But we can precompute for each x (1..300) an array of powers up to n, but that's large (3004e5 ~ 120M). 120M 32-bit integers ~ 480MB, too much. Alternatively, we can note that x <= 300, and lengths are up to 4e5. We could compute for each x a vector of its powers at exponent that are powers of two, and combine them to compute any exponent quickly. But still we need to compute x^len for many different len values across nodes. However, the nodes have fixed lengths; we could precompute for each distinct length that appears in the segment tree, the powers of each x? The segment tree has O(n) nodes, each with a specific length (the size of its segment). The number of distinct lengths is about O(log n) different lengths? Actually in a segment tree built on n, the lengths of nodes are powers of two or something? For a segment tree built on a size n, node intervals have lengths that are either powers of two or sums? Typically, for a perfect binary tree with size next power of two, nodes have lengths that are powers of two. However, if n not power of two, lengths vary. But the number of distinct segment lengths in a segment tree is O(log n). Because the tree recursively splits, lengths are like floor(n/2^k) etc. Actually the number of distinct lengths is about O(log n). For example, a segment tree on [1,n] where n is arbitrary, the possible segment lengths are all numbers that appear as size of a node. Typically the set of lengths is at most 2log2(N) maybe. Because each depth corresponds to a certain length range. Actually we can prove: In a segment tree, each node corresponds to an interval length that is a power of two times some factor? But more concretely, for n up to 4e5, the number of distinct lengths is relatively small, maybe up to about 2log2(4e5) ~ 40? Possibly. Let's analyze: In a segment tree built recursively, the lengths are of the form: for each node, length = r-l+1. The recursion splits into two parts roughly half. For a given n, the lengths that appear are exactly the sizes of intervals in the recursive partition. Those are determined by the binary representation of n. Typically the number of distinct lengths is O(log n). For example, n=4e5, the recursion will produce intervals of sizes that are powers of two and also some leftovers. In practice, the distinct sizes could be up to about 2log2(n) ≈ 40. So we could precompute for each x and each distinct length L the value x^L % MOD. Then during updates, for a node of length L, we can quickly get x^L from precomputed table.
Thus we can: Build segment tree, and for each node store its length. Then we collect all distinct lengths occurring in nodes (there are O(log n) but actually up to 2log2(N) maybe 20-30, but we can compute it). For each x from 1 to 300, precompute pow_x[L] for each distinct L. That would be at most (300 * distinct_lengths) entries. distinct_lengths <= 2ceil(log2(n))? Let's compute max distinct lengths: In segment tree, nodes are intervals covering a range. For any n, the segment tree built by standard recursion (like in CP) creates a tree with nodes representing intervals of various sizes. The number of distinct interval lengths is at most O(log n) because each recursive call either splits into halves. More precisely, the sizes are either 1 or some other sizes; they can be many if n is not power of two? Actually consider n=7: intervals: root length 7, left child length 4, right child length 3, then further splits: from 4: left 2, right 2; from 3: left 2, right 1. So distinct lengths: 7,4,3,2,1 -> 5, which is still O(log n) as log2(7)≈2.8, 5 is about 2log2(7). For n=10^5, distinct lengths may be around 2log2(n) ~ 34. So we can precompute for each x (1..300) an array mapping length index to pow. That's 300*~40=12,000 entries, trivial.
Thus we can optimize product segment tree updates: For each node, we know its length len (r-l+1). When applying factor x, we can compute pow_x_len = precomputed pow[x][len_index] or directly from an array pow_x_len[distinct_len_id]. But we need to map length to an index. We can precompute a map from length to index, and for each node store idx_len. Then when updating with x, we do node.val = node.val * pow[x][idx_len] % MOD. pow[x][idx_len] is precomputed as (x^len) % MOD.
We must also precompute inverse for each prime p, and factor (p-1)*inv(p) % MOD.
Now building prime bitset segment tree: Each leaf i: we need initial mask for a_i (distinct primes dividing a_i). We can precompute for each number 1..300 a bitmask of primes. Precompute list of primes up to 300, assign each prime an index (0..61). Then for each number, factorize (or compute mask by checking primes ≤ number). Since numbers ≤300, we can precompute mask[1..300] using prime list.
Then build segment tree: combine child masks with bitwise OR. Lazy mask initially 0.
Range OR update: For node covering segment length L, we do node.mask |= mask (since OR with mask). node.lazy |= mask. When pushing down, if node.lazy != 0, we OR child masks with node.lazy, and OR child lazy with node.lazy. Then set node.lazy = 0.
Query OR: returns OR mask over range.
Now product segment tree: each leaf stores a_i % MOD. Build as standard.
Range multiply: For node fully in range, apply multiplication: node.val = node.val * pow_x_len[node.len_idx] % MOD; node.lazy = node.lazy * x % MOD.
Push down: if node.lazy != 1, push to children: apply same multiplication factor to each child using its length, and multiply child lazy by node.lazy. Then set node.lazy = 1.
Query product: standard.
Now we need to compute pow_x_len for all distinct lengths. We'll first build the segment tree for product and store for each node its length (or length index). Since both trees have same structure (they are separate trees but both built on the same n and same node intervals). We could also combine them in one tree, but separate is simpler.
To get distinct lengths, we could just compute pow for each x for all possible len up to n? Not necessary; we can compute on the fly using fast exponentiation. But we want to avoid O(log len) per node. Let's consider whether fast exponentiation per node is acceptable. With q=2e5, each multiply updates ~log n nodes ~ 19, each node requires pow(x, len) which is O(log len) ~ 19 multiplications, total per update ~361 modular multiplications. With 2e5 updates (worst-case all are multiply), that's 72.2e6 multiplications. That's actually fine; 72 million modular multiplications in C++ should be well under time (maybe < 0.5 sec?). But we also have other operations. However, we also need to consider that there may be up to 2e5 multiply queries, but not all are multiply; some are totient. So maybe it's fine. But we can also precompute for each x the powers for all len that appear, which is easy and reduces to O(1) per node. So I'll implement the precomputed method to be safe.
Implementation plan:
-
Define MOD = 1e9+7.
-
Precompute primes up to 300. Let vector primes; assign each prime an index 0..P-1 (P = 62).
-
Precompute for each prime p: inv[p] = mod_inv(p); factor[p] = (p-1) * inv[p] % MOD.
-
Precompute mask_for_num[301] (64-bit). For num from 1 to 300: mask=0; for each prime index i, if num%prime==0: set bit i. (Note: distinct primes only, even if multiple factors.)
- Actually we need only distinct primes. So while factoring we can set bits for each prime dividing num. Since numbers are small, we can precompute by checking all primes.
-
Read n, q.
-
Read array a[1..n].
-
Build segment tree for product:
- We'll implement iterative segment tree or recursive. With lazy, recursive might be easier. But given n up to 4e5, recursion depth O(log n) is fine. However, building recursively for 4e5 may cause recursion overhead but acceptable if iterative? But recursive with 4*n nodes is okay. We'll likely need lazy propagation; recursive with push and update functions.
But careful: recursion depth for segment tree of size 4e5 is about ~19, fine.
However, number of function calls for building and many queries may be high but still okay.
Alternatively, we can implement segment tree with arrays (struct) and iterative lazy? I'd go with recursive to simplify.
But we need two trees: one for product, one for mask. Could combine into one struct that stores both? Possibly, but separate simpler.
But we have to ensure we use the same tree ranges; we can create a class SegmentTree with template or two separate implementations.
We'll design:
class SegTreeProd {
int n;
vector tree; // product modulo MOD
vector lazy; // multiplier, initialized 1
vector len; // length of segment for each node, maybe not stored if we compute on the fly
// We'll store left, right in recursion? Usually we pass l,r and compute len = r-l+1.
// But for lazy updates we need length to compute power. If we use recursive functions, we can compute length on the fly as (r-l+1). So we don't need to store lengths. In that case, we need to compute x^len quickly. We could compute pow(x, len) using fast exponentiation with precomputed powers? But we can still use precomputed pow per length if we know the length. But we can also compute pow by binary exponentiation O(log len). Since len varies up to n, and we have many updates, it might be okay. But we can also precompute an array pow_x_len for all possible lengths? That's 4e5 possible lengths. But we could precompute for each x its powers up to n, but 300*4e5=120M, maybe borderline but possible if we use int (4 bytes) -> 480MB, too big. So we either accept O(log len) exponentiation or use precomputed per node length.
Recursive segment tree with l,r passed, we can compute len = r-l+1. To get precomputed pow, we need to map len to an index. Since len is not constant per node (but each node has a fixed len depending on its interval). In recursive implementations, each node corresponds to a specific segment length. So we could store for each node its length (or its precomputed powers?) in an array. Or we could compute the exponent on the fly using fast pow, which is O(log len) per node update.
Given that log len ≤ 19, 19 multiplications per node, 19 nodes per update => 361 multiplications, 2e5 updates => 72M multiplications. Each multiplication mod is cheap. Should be fine. Also totient queries involve product query (traverse nodes) and mask query (traverse nodes) and then iterate over bits (max 62). So total operations maybe ~200M, still within 2 seconds? Might be okay in C++ with optimizations. But to be safe, we can optimize further.
We can also compute pow(x, len) using precomputed powers of x for all possible lengths? Since len up to 4e5, and x up to 300, 120M numbers might be memory heavy. But we can note that we only need powers for len that actually appear in node updates. The number of distinct node lengths is about 2*log2(n) ~ 40. So we could precompute for each x a vector of size distinct_length_count. To do that, we need to know the distinct lengths in the segment tree before building. We can either build the tree and then record lengths, or we can precompute lengths from the tree building process. Since we are coding recursively, we can during building store the length for each node index. Then after building, we can compile a set of lengths, map them to indices, and precompute pow_table[x][idx] for each x. But then during updates we need to know for a given node its length index to fetch pow quickly. We can store an array lenIdx[node] mapping node index to index in distinct length list. This is doable.
Simpler: use iterative segment tree with lazy? Not trivial for range multiply and range product. I'll stick with recursive and fast exponentiation for simplicity. Let's estimate: 72M modular multiplications. Each modular multiplication is a 64-bit multiply and mod, maybe a few CPU cycles. 72M is fine (<0.5 sec). However, there is also overhead for function calls and recursion. We can optimize by using iterative segment tree? There is a known structure for range multiplication and range product using Fenwick tree with point updates? Not directly.
But careful: MULTIPLY updates require updating both product and mask trees. Each multiply will cause O(log n) updates in both trees. So total node visits: 2 * 2e5 * log n ≈ 22e519=7.6M node visits for updates. In each product node update, we compute pow(x, len) which is O(log len) => about 19 multiplies -> total multiplies 7.6M19? Wait, 7.6M node visits? Actually each multiply updates both trees. For product tree, we visit O(log n) nodes, each requiring exponentiation O(log len). So total exponentiations = number of product node updates * O(log len). Number of product node updates: up to q * O(log n) = 2e519 = 3.8M nodes. Each exponentiation O(log len) ~ 19, so total modular multiplications for exponentiation = 3.8M * 19 ≈ 72.2M. Additionally, we also have multiplication for applying lazy: node.val = node.val * pow_x_len % MOD, which uses one multiply. That's separate. So total modular multiplications maybe around 100M. That's still okay.
But there is also query operations. q up to 2e5, each query visits O(log n) nodes in both trees: about 22e519=7.6M node visits. Each product query node combines with multiply. So total operations maybe 100M-200M, still acceptable in C++ with optimized code (e.g., using int, avoiding recursion overhead? But recursion might be slower). However, we need to be careful about recursion depth and function call overhead. For each node visited we call a recursive function, which might be slower.
Alternative: implement iterative segment tree with lazy propagation? That's more complex but possible. I'll consider implementing segment tree using arrays and iterative methods for range updates and range queries? There is a common pattern: segment tree with lazy using 2n size? Actually for range updates and range queries, we can use a segment tree stored as an array of size 2N and lazy as another array, but updates and queries are still O(log N) with loops. That is often efficient.
Let's design an iterative segment tree with lazy for product. For range multiply and range product, we can use a segment tree with size = power of two, store values in tree[n..2n-1], and lazy in separate array of size n (or 2n). Standard lazy propagation with push function for each visited node can be iterative but often involves recursion. I'm more comfortable with recursive segment tree. Given constraints, recursive should be fine if we implement efficiently (e.g., inline functions, pass by reference). 2e5 queries * log n * recursion overhead might be okay.
I'll implement recursive segment tree with arrays and functions:
For product:
vector prod, lazy; // size 4*n
build(int node, int l, int r)
update(int node, int l, int r, int ql, int qr, int x)
query(int node, int l, int r, int ql, int qr)
We'll compute len = r-l+1 inside update when applying.
To compute pow(x, len) fast, we could precompute all powers of x up to n? But memory large. But we can compute using fast exponentiation each time.
But we can also precompute a table pow_x_len for each x for all possible lengths that appear. Since the number of distinct lengths is small, we can compute after building by traversing nodes. However, our recursive update will need to know pow(x, len) for the node's length. If we store for each node its length (or precomputed pow for each x?), we could compute once per node per update. Precomputing for each node a vector of pow for each x? That would be huge. Better to compute on the fly.
Given that exponentiation is cheap, we can just use fast pow.
However, we must note that exponent len can be up to 4e5, and we call fast pow many times. But fast pow uses O(log len) multiplications. We can improve by precomputing powers of each x for exponent up to n using binary exponentiation? Not needed.
But careful: In each node update we need to compute x^len % MOD. This is the same for nodes with same len. Many nodes share same len. For example, in a segment tree of size n (next power of two), many nodes have lengths that are powers of two. So we can precompute for each x a map from length to pow. But to avoid complexity, we can compute on demand and cache? But we can also compute all needed powers at the start: First, collect all distinct lengths in the segment tree (by traversing the tree). There will be O(log n) distinct lengths. Then for each x from 1 to 300, compute pow_x[len] for each distinct len. Then store an array mapping length to index. Then in the update, we retrieve lenIdx for node (store an array lenIdx[node] or compute length on the fly and use an unordered_map from length to pow? But length is integer, we can use an array powX[301][maxLenIndex] but we need to know length quickly.
Simplest: compute on the fly with fast pow. I'll go with that for now, but we should ensure it's efficient.
But we have another tree for mask. For mask we use OR lazy. That is simpler.
Now we need to handle the queries.
Implementation Steps:
-
Precompute primes up to 300. We'll create a vector primes; a bool array isPrime[301]; sieve.
-
For each prime, assign index 0..P-1, store its value p, inv(p), factor = (p-1)*inv(p)%MOD.
-
Precompute mask_for_num[301] as uint64_t. For each num from 1 to 300, mask = 0; for each prime idx, if num % primes[idx]==0: mask |= (1ULL << idx).
-
Read n, q.
-
Read array a[1..n].
-
Build product segtree:
We'll create class SegTreeProd:
int n;
vector tree;
vector lazy;
void build(int node, int l, int r, vector& a) {
if(l == r) { tree[node] = a[l] % MOD; lazy[node] = 1; return; }
int mid = (l+r)/2;
build(node2, l, mid, a);
build(node2+1, mid+1, r, a);
tree[node] = tree[node2] * tree[node2+1] % MOD;
lazy[node] = 1;
}
void apply(int node, int l, int r, long long x) {
// apply multiplication by x to this node
// tree[node] = tree[node] * x^{len} % MOD
int len = r - l + 1;
long long pow_x_len = power(x, len);
tree[node] = tree[node] * pow_x_len % MOD;
lazy[node] = lazy[node] * x % MOD;
}
void push(int node, int l, int r) {
if(lazy[node] != 1) {
int mid = (l+r)/2;
apply(node2, l, mid, lazy[node]);
apply(node2+1, mid+1, r, lazy[node]);
lazy[node] = 1;
}
}
void update(int node, int l, int r, int ql, int qr, int x) {
if(ql <= l && r <= qr) {
apply(node, l, r, x);
return;
}
push(node, l, r);
int mid = (l+r)/2;
if(ql <= mid) update(node2, l, mid, ql, qr, x);
if(qr > mid) update(node2+1, mid+1, r, ql, qr, x);
tree[node] = tree[node2] * tree[node2+1] % MOD;
}
long long query(int node, int l, int r, int ql, int qr) {
if(ql <= l && r <= qr) return tree[node];
push(node, l, r);
int mid = (l+r)/2;
long long res = 1;
if(ql <= mid) res = res * query(node2, l, mid, ql, qr) % MOD;
if(qr > mid) res = res * query(node2+1, mid+1, r, ql, qr) % MOD;
return res;
}
We need power function: long long power(long long x, int p) mod MOD. Use fast exponent.
Now mask segtree: class SegTreeMask
using ull = unsigned long long;
vector tree; // OR mask
vector lazy; // mask to OR
void build(int node, int l, int r, vector& a) {
if(l == r) { tree[node] = a[l]; lazy[node] = 0; return; }
int mid = (l+r)/2;
build(node2, l, mid, a);
build(node2+1, mid+1, r, a);
tree[node] = tree[node2] | tree[node2+1];
lazy[node] = 0;
}
void apply(int node, int l, int r, ull mask) {
tree[node] |= mask;
lazy[node] |= mask;
}
void push(int node, int l, int r) {
if(lazy[node]) {
int mid = (l+r)/2;
apply(node2, l, mid, lazy[node]);
apply(node2+1, mid+1, r, lazy[node]);
lazy[node] = 0;
}
}
void update(int node, int l, int r, int ql, int qr, ull mask) {
if(ql <= l && r <= qr) {
apply(node, l, r, mask);
return;
}
push(node, l, r);
int mid = (l+r)/2;
if(ql <= mid) update(node2, l, mid, ql, qr, mask);
if(qr > mid) update(node2+1, mid+1, r, ql, qr, mask);
tree[node] = tree[node2] | tree[node2+1];
}
ull query(int node, int l, int r, int ql, int qr) {
if(ql <= l && r <= qr) return tree[node];
push(node, l, r);
int mid = (l+r)/2;
ull res = 0;
if(ql <= mid) res |= query(node2, l, mid, ql, qr);
if(qr > mid) res |= query(node2+1, mid+1, r, ql, qr);
return res;
}
We'll need to create initial masks for leaves: for i from 1..n, maskArr[i] = mask_for_num[a[i]].
Now processing queries:
For each query:
if type == "MULTIPLY": read l,r,x.
productTree.update(1,1,n,l,r,x);
mask = mask_for_num[x];
if(mask != 0) maskTree.update(1,1,n,l,r,mask);
(If mask==0, nothing to do for mask tree)
else "TOTIENT": read l,r.
prod = productTree.query(1,1,n,l,r) % MOD;
mask = maskTree.query(1,1,n,l,r);
ans = prod;
while (mask) {
int i = __builtin_ctzll(mask); // index of least significant set bit (0-based)
// i corresponds to prime index
ans = ans * factor[i] % MOD; // factor[i] = (primes[i]-1)*inv(primes[i]) % MOD
mask &= mask - 1; // clear lowest set bit
}
print ans.
We need to be careful about long long for product; use mod.
Now complexity: Each totient query does a product query (O(log n)) and mask query (O(log n)) plus loop over set bits (<=62). So O(log n + 62). Multiply: O(log n + number of prime factors of x) for mask update, product update O(log n) with exponentiation per node.
Potential issues: For mask tree, we use OR lazy. When we apply mask to a node, we OR node's mask and lazy. However, is it correct to just OR for apply? Consider node representing a segment that already has some bits set. After we set mask bits for all elements, the OR of the segment becomes node.mask | mask. That's correct. For lazy propagation, we need to combine multiple pending OR updates: If we already have a lazy mask L, and we receive new mask M, then the effective lazy becomes L | M. Because we need to apply OR M after previous ORs. Since OR is idempotent and order doesn't matter, we can just OR. So apply: lazy[node] |= mask. That's fine.
But careful: When we push lazy down to children, we need to apply the parent lazy to children. That is: child.mask |= parent.lazy; child.lazy |= parent.lazy. That's correct.
Now, about the product tree: When we push lazy, we apply the stored lazy multiplier to children. The children's segment product should be multiplied by lazy^len_child, and their lazy multiplied by lazy. We'll implement apply function that multiplies node's value by (x^len) and node's lazy by x. push then calls apply on children with lazy[node].
But we must be careful: The lazy value stored in node is the multiplier that needs to be applied to the whole segment, but hasn't been applied to children. So push: apply(child, lazy[node]), then set lazy[node]=1.
Now potential pitfall: In product tree, the apply function uses power(x, len) each time. For a leaf node, len=1, so pow(x,1)=x. For internal nodes, we compute x^len.
But for large number of updates, repeated exponentiation for the same node with same x may cause repeated calculations. But okay.
We also need to consider that x may be 1, in which case we can skip? For product tree, multiply by 1 does nothing. For mask tree, mask_for_num[1] = 0, so nothing. So we can skip if x==1? But it's fine to process.
Now we need to handle modulo operations efficiently.
Now for the power function: We'll precompute maybe powers for all x for exponents up to 20? Not.
We'll implement:
long long power(long long a, int b) {
long long res = 1;
while(b) {
if(b&1) res = res * a % MOD;
a = a * a % MOD;
b >>= 1;
}
return res;
}
But note: x can be up to 300, len up to 4e5, so exponent can be large. Fast pow works.
But we must be careful: In product tree update, we might call apply(node, l, r, x) multiple times for the same node. That's fine.
Edge Cases: Multiplication may cause product to exceed 64-bit before mod? We use long long and mod after multiplication. product values always mod MOD.
Now about mask tree: we use unsigned long long (64-bit). There are 62 primes, so fits in 64-bit. We'll use uint64_t from . We need to left shift by up to 61, so 1ULL << idx.
Now about initial building: For product tree, initial values a_i mod MOD. Since a_i ≤300, fine.
Now, we need to be careful with recursion depth and stack size. n=4e5, recursion depth for building is about 2*log2(n) ~ 20, but recursion for query/update traverses depth first, depth also ~20. So no problem.
But we need to allocate arrays of size 4n for each tree. For n=4e5, 4n = 1.6e6. That's okay.
Now test with example.
Let's simulate:
n=4, a=[5,9,1,2]
primes: 2,3,5,7,... mask_for_num: 5 -> primes:5 => bit for 5 (index? 2->0? Let's assign index: 0 for 2, 1 for 3, 2 for 5, 3 for 7, ...). So mask(5)= 1<<2 = 4? But we only care about bits. 9 -> 3^2 => mask bit for 3. 1 -> 0, 2-> mask for 2.
First query TOTIENT 3 3: product=1, mask=0 -> ans=1.
Second TOTIENT 3 4: product=12=2, mask for 2? mask includes 2? Actually a_3=1 no bits, a_4=2 mask for 2. So mask=bit0, factor = (2-1)/2=1/2? Actually (1 - 1/2)=1/2, but modularly: (2-1)inv2 = 1inv2 = 500000004 mod MOD. So ans = 2 * inv2 = 1 mod MOD. correct.
Third MULTIPLY 4 4 3: update product multiply 23=6, mask for 3 (bit1) OR onto position 4. So leaf mask becomes (2) | (3) = bits for 2 and 3.
Fourth TOTIENT 4 4: product=6, mask includes 2 and 3. ans = 6 * (1-1/2)*(1-1/3) = 6 * 1/2 * 2/3 = 6 * 1/3 = 2 mod. correct.
Works.
Now about overflow in mask tree: uint64_t enough.
Potential issues: When we update mask tree with mask, we need to ensure that the mask for x includes only distinct primes. So mask_for_num[x] must be based on distinct primes. Good.
Now consider multiplication: If we multiply a range by x, the product tree updates accordingly. But what about the mask tree? For each element in range, we OR its mask with mask_for_num[x]. Since we are only tracking distinct primes present in each element, this is correct because after multiplication, the prime factors of x are added to that element's factor set. However, note that if an element already had those primes, OR doesn't change. So yes.
Now we should confirm that we don't need to track exponents of primes. The totient only depends on distinct primes. So boolean is sufficient.
Thus algorithm is correct.
Now let's think about potential pitfalls: When we multiply by x, the product might become huge, but modulo keeps it. The mask tree only deals with presence.
But there is one subtlety: The totient formula uses distinct primes dividing the product. However, if the product contains a prime factor that appears only from multiplication, but that multiplication might be applied to multiple elements. The mask OR across range will capture that prime if at least one element in the range has it. That's correct.
Now consider scenario: a_i = 1, initially mask 0. Multiply by 2: now a_i=2, mask becomes {2}. Multiply by 2 again: a_i=4, mask remains {2}. OR with mask for 2 (which is {2}) again does nothing. So still correct.
Now, about the lazy propagation in mask tree: Since updates are only OR, and we never reset bits, the lazy propagation as described works.
But careful: When we push lazy from a node to its children, we apply the parent's lazy mask to the children. However, the children may have their own lazy masks. Since we OR them, that's fine. But we must ensure that after pushing, the parent's lazy is cleared. This is standard.
Now, the product tree lazy multiplication: It's standard.
Now implementation details:
-
Use fast I/O (scanf/printf or cin with sync). We'll use scanf/printf for speed.
-
Since we need to parse queries: they are strings. Either read with scanf: char op[10]; scanf("%s", op); then if op[0]=='M'? Actually "MULTIPLY" and "TOTIENT". They start with 'M' and 'T' respectively. So we can read first char and decide.
But careful: MULTIPLY has first char 'M', TOTIENT has 'T'. So read string s; if s[0]=='M' then read l,r,x; else read l,r.
We'll use char type[10]; scanf("%s", type).
Now about indexing: we use 1-indexed arrays for the segment tree.
Now, memory: For product tree: tree and lazy arrays of size 4*n = 1.6e6 each, each 8 bytes -> ~12.8 MB each? Actually 1.6e6 * 8 = 12.8 MB. For mask tree: tree and lazy arrays of uint64_t also 1.6e6 * 8 = 12.8 MB each. Total ~51.2 MB. Acceptable.
But we also store other arrays (a, maybe mask initial) but small.
Now, we need to ensure that the recursive functions are not too slow. We could implement iterative segment tree to reduce overhead. But I think recursion is fine.
Potential performance bottleneck: In product tree update, we compute power(x, len) many times. If we have many updates, the power function may be called many times. Could we precompute powers for each x for all len values that appear? Let's try to implement that optimization to reduce constant factor.
We can compute distinct lengths from the segment tree building process. For each node we can store its length. We can store length array of size 4n. But we can also compute on the fly (r-l+1). However, to use precomputed power, we need to map length to precomputed power value for given x. Since the length is known at update time, we could compute power using fast exponentiation; but we could also precompute for each length a vector of powers for x from 1..300? Actually we need pow(x, len) for given x and len. The number of distinct lengths is small (like maybe up to 2ceil(log2(n)) + something). Let's compute maximum distinct lengths for n=4e5. In a segment tree built on [1,n] recursively, the intervals are all subsegments of the form [L,R] where size is a power of two or combination. Actually the set of lengths that appear is exactly the set of all lengths of nodes in the segment tree. The segment tree is a full binary tree where each node corresponds to a segment