Sorry, I transcribed the last case of the mathematical version of the solution incorrectly; it'should have been (f(n-q, p) - r)(p/(1-p)). A clearer statement is as follows:
let q(n, p) = (q - r(n, p))/p,
r(n, p) = n (mod p),
g(n, p) = f(n - q(n, p), p) - r(n, p)
then f(n, p) is defined piecewise as:
0, n = 1
f(n - 1, p) + p (mod n), n < p
g(n, p) + n, g(n, p) < 0
g(n, p) + q(g(n, p), p - 1)) otherwise.
My e-mail address is dkturner@gmail.com, let me know if you need further explanation, and especially if you have a better way of stating the definition of f :-)