TITLE: Iterations of modulus operation
QUESTION [5 upvotes]: While working on a completely unrelated task, I thought up the following problem:

Consider the following process.  Let $a_0$ and $n$ be given, and determine $a_1,\ldots, a_k$ as follows:
  $$a_{j+1} = n \text{ mod } a_j$$
  ...where the process terminates when $a_j \mid n$.  That is, $a_k = 0$. 
Define $f(a_0, n) = k$.
Aside from direct iteration, how might one compute or express $f(a_0, n)$?

Example: $f(124323, 938342) = 12$
68081 = 938342 mod 124323
53289 = 938342 mod 68081
32429 = 938342 mod 53289
30330 = 938342 mod 32429
28442 = 938342 mod 30330
28198 = 938342 mod 28442
 7808 = 938342 mod 28198
 1382 = 938342 mod 7808
 1346 = 938342 mod 1382
  180 = 938342 mod 1346
    2 = 938342 mod 180
    0 = 938342 mod 2

This process always terminates (as can be trivially proven).  
Aside from the obvious $f(n\pm1, n)$ case, I don't really know where to begin approaching this--problems I just think up tend to be harder than the math I know. ;)
So, my questions are:
1) Obviously, if someone sees an obvious route to computing this, that would be great.
2) If this is something that is known to be impossible, that would also be good to know.
3) If someone has a hint, I'd appreciate that--I like trying to figure things out, but I know that good hints can be difficult to write.

REPLY [4 votes]: This is what I call Gauss's algorithm for computing inverses, when $n = p$ prime. By replacing $a$ by $a' := n\ {\rm mod}\ a = n - qa\,$ it yields $a'\equiv -qa\,$ which is a smaller multiple of $a$. Iterated, it yields a descent on the elements of the ideal $(a)$ of all multiples of $a$ mod $n$. It terminates with a factor of $n$. This factor can only be $1$ when $n = p$ is prime,  so it shows that $1$ is a multiple of $a$, by the product of the  sequence of quotients $q_i,\,$ so yielding $\,a^{-1}$ mod $n$.