Merging Amulets

To solve this problem, we will use the fact that $$$\mathtt{gcd}$$$ changes at most $$$\log A$$$ times, where $$$A$$$ is the maximum value among $$$a_i$$$. We will find the prefix and suffix $$$\mathtt{gcd}$$$, denoting them as $$$p_i$$$ and $$$s_i$$$, respectively.

We will divide the calculation of the final sum of $$$\mathtt{gcd}$$$ into 3 stages:

  1. The segment $$$[1, n]$$$, to find the answer we need to calculate the $$$\mathtt{lcm}$$$ of the entire array. This can be done using the Sieve of Eratosthenes and prime factorization of each element;

  2. Segments $$$[i, j]$$$ such that $$$p_i = p_{i+1}$$$ and $$$s_{j-1} = s_j$$$. The answer for such segments will be $$$\mathtt{gcd}(p_i, s_j)$$$, since $$$\mathtt{lcm}$$$ will definitely be divisible by $$$\mathtt{gcd}(p_i, s_j)$$$, and the final $$$\mathtt{gcd}$$$ cannot exceed this value. Such segments can be counted quickly if we know in advance the positions where $$$p_i$$$ and $$$s_j$$$ change;

  3. The remaining segments, specifically those $$$[i, j]$$$ such that $$$p_i \neq p_{i+1}$$$ or $$$s_{j-1} \neq s_j$$$, since $$$\mathtt{gcd}$$$ changes at most $$$\log A$$$ times, there will be at most $$$O(n \log n)$$$ such segments. Therefore, they can be counted with a straightforward pass through the array.

The final answer will consist of the sum of all three types of segments.