Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Hints : A Simple GCD Problem (Easy Version)

The condition requires preserving $\gcd(a_l, \ldots, a_r)$ for every subarray — that is a huge number of constraints. Can you find a much smaller set of values whose preservation implies all of them?
Answer to Hint 1: Define $g_i = \gcd(a_i, a_{i+1})$ for each consecutive pair. One can show that $\gcd(a_l, \ldots, a_r) = \gcd(g_l, g_{l+1}, \ldots, g_{r-1})$, so preserving every subarray GCD is equivalent to preserving every consecutive-pair GCD $g_i$. Now, for a single position $i$, what divisibility constraint does this place on $a’_i$?
Answer to Hint 2: Position $i$ participates in the pair $(i-1, i)$ requiring $g_{i-1} \mid a’_i$, and the pair $(i, i+1)$ requiring $g_i \mid a’i$. So $a’i$ must be a multiple of $L_i = \operatorname{lcm}(g{i-1}, g_i)$ (using only the relevant neighbor for endpoints). Since $g{i-1} \mid a_i$ and $g_i \mid a_i$, we always have $L_i \mid a_i$. But we also need $\gcd(a’i, a’{i+1})$ to equal $g_i$ exactly — not just be a multiple. What happens if we set every $a’_i = L_i$ (the smallest valid multiple)?
Answer to Hint 3: Setting every position to its $L_i$ is always safe. The proof uses a lattice identity: $\gcd(\operatorname{lcm}(a,b),; \operatorname{lcm}(b,c)) = \operatorname{lcm}(b,; \gcd(a,c))$. Applied with $a = g_{i-1},; b = g_i,; c = g_{i+1}$ gives $\gcd(L_i, L_{i+1}) = \operatorname{lcm}(g_i,; \gcd(g_{i-1}, g_{i+1}))$. The key fact is $\gcd(g_{i-1}, g_{i+1}) \mid g_i$ — can you see why?
Answer to Hint 4: For any prime power $p^k$: $v_p(g_{i-1}) \leq v_p(a_i)$ (since $g_{i-1} \mid a_i$) and $v_p(g_{i+1}) \leq v_p(a_{i+1})$ (since $g_{i+1} \mid a_{i+1}$). Therefore $\min(v_p(g_{i-1}), v_p(g_{i+1})) \leq \min(v_p(a_i), v_p(a_{i+1})) = v_p(g_i)$. This gives $\gcd(g_{i-1}, g_{i+1}) \mid g_i$, so $\gcd(L_i, L_{i+1}) = g_i$. The strategy “replace every $a_i$ with $L_i$” preserves all GCDs. In C1 where $b_i = a_i$, at which positions can you actually perform an operation?
Answer to Hint 5: An operation at position $i$ needs some $m \neq a_i$ with $L_i \mid m$ and $1 \leq m \leq b_i = a_i$. The multiples of $L_i$ in $[1, a_i]$ are $L_i, 2L_i, \ldots, a_i$. If $a_i = L_i$ (i.e., $a_i$ already equals the required LCM), the only such multiple is $a_i$ itself, so no valid $m$ exists. If $a_i > L_i$, we can pick $m = L_i$. Since changing to $L_i$ never conflicts with any neighbor, the answer is simply the number of indices $i$ where $a_i \neq L_i$, computable in $O(n)$.