Official

E - Divide Both Editorial by en_translator


Let us count the number of pairs for each GCD (Greatest Common Divisor) \(g\) of \(x, y\).

First, let us forget about the conditions \(\frac{x}{g}\neq 1,\ \frac{y}{g}\neq 1\) and only care the condition \(g\neq 1\).

Question: For each \(k=2,3,\ldots,R\), count the number of pairs \(L\leq x,y\leq R\) such that \(\gcd(x,y)=k\)

This problem can be solved almost as same way as ABC162E Sum of gcd of Tuples (Hard).

\(\gcd(x,y)\) is a multiple of \(k\) if and only if both \(x\) and \(y\) are multiples of \(k\). The number of multiples of \(k\) between \(L\) and \(R\) (inclusive) are \(X_k:=\left\lfloor\frac{R}{k}\right\rfloor-\left\lfloor\frac{L-1}{k}\right\rfloor\), so the number of pairs \(L\leq x,y\leq R\) such that \(\gcd(x,y)\) is a multiple of \(k\) is \(X_k^2\).
\(\gcd(x,y)\) is exactly \(k\) if and only if “\(\gcd(x,y)\) is a multiple of \(k\), but not \(2k,3k,\ldots\).” Therefore, these can be computed in the decreasing order of \(k\).

Finally, let us subtract the number of pairs that does not satisfy the condition \(\frac{x}{g}\neq 1,\ \frac{y}{g}\neq 1\).

That “\(\gcd(x,y)=g\) and ‘one of the \(\frac{x}{g}\neq 1,\ \frac{y}{g}\neq 1\) is not satisfied’ ” is equivalent to that “\(\gcd(x,y)=g\) and ‘\(x=g\) or \(y=g\)’ “. Since \(x\) and \(y\) are both multiples of \(g\), the number of such pairs is \(\max(2,L)\leq g \leq R\) if \(\max(2,L)\leq g \leq R\), or otherwise \(0\).

Now we have solved the problem. The complexity is \(O(R\log R)\), where the bottleneck is finding the number of pairs such that \(\gcd(x,y)=k\).

posted:
last update: