if you simulate this program with different values of n and r, notice that this function foo(n,r) gives the sum of digits of n(when it is converted to base r).
Like if n=513, r=14 then $(513)_{10}=(289)_{14}$ and 2+8+9=19 and this is the output of the program.