D - Count Subtractions Editorial by spheniscine


Assume \(A > B\), otherwise we swap them.

If we perform the procedure in the statement naively, it could take a large number of steps if \(A\) is much larger than \(B\). Thus, we should shortcut it by noticing we can take \(\lceil \frac{A}{B} \rceil - 1\) steps before \(A \le B\) and we have to either terminate or swap and repeat. We could simulate these steps at once using division and multiplication, and update \(A\) and the answer accordingly.

Does this improved algorithm terminate fast enough? It turns out that after one step of the improved algorithm, either \(A \larr B\), in which case the algorithm terminates, or \(A \larr A \text{ mod } B\), which might remind you of the Euclidean algorithm to find the greatest common divisor (GCD). Indeed, this algorithm will terminate in \(O(\log A)\) just as in the Euclidean GCD algorithm, and the final values of \(A\) and \(B\) are equal to the GCD of the original \(A\) and \(B\).

posted:
last update: