# Euclidean algorithm on $(a^n-1,a^m-1)$

I'm having trouble applying the Euclidean algorithm to $$\gcd(a^n-1,a^m-1)=a^{\gcd(n,m)}-1$$ I've seen others do it such as in this solution but I'm having trouble figuring out what they are doing in each step.

Could someone help explain this to me?

Assume that $n=qm+r$. Then $a^n-1 = a^r\cdot(a^m)^q-1$, and since $$a^m \equiv 1 \pmod{a^m-1} \tag{1}$$ we have: $$(a^n-1) \equiv (a^r-1)\pmod{a^m-1}\tag{2}$$ proving: $$\gcd(a^n-1,a^m-1) = \gcd(a^r-1,a^m-1).\tag{3}$$ Now, repeat. The involved exponents transform like in the computation of $$\gcd(n,m) = \gcd(r,m) = \ldots \tag{4}$$ hence at last we get: $$\gcd(a^n-1,a^m-1) = a^{\gcd(n,m)}-1\tag{5}$$ qed.