TITLE: Recursion with Random number?
QUESTION [6 upvotes]: function foo(n)  
     if n = 1 then  
        return 1  
     else  
        return foo(rand(1, n))  
     end if  
   end function  

If foo is initially called with m as the parameter, what is the expected number times that  rand() would be called ? 
BTW, rand(1,n)  returns a uniformly distributed random integer in the range 1 to n.

REPLY [5 votes]: This is very similar to user44197's answer. 
Let $G(m)$ be the expected numbers of total calls to rand when foo(m) is executed.
We see that $G(1)=0$ and $G(2)=1 + G(2)/2 \implies G(2)=2$
For $m>2$ there are two possible events: that the first rand() returns the same number m (probability $m$), or not. In the second case, the follow-up is equivalent as if the argument m-1 were passed.
Hence  $$G(m) = \frac{1}{m}(G(m)+1) +  \frac{m-1}{m} G(m-1)$$
So
$$G(m)=G(m-1)+\frac{1}{m-1}$$
Eg $G(3)=2 + 1/2$, $G(4)=2 + 1/2 + 1/3$, or
$$G(m) = 1 + H_{m-1}$$ 
where $H_n$ is the harmonic number.