This is an old homework problem from my algorithms class. I have the solution to the problem, but even after repeated attempts, I fail to understand how to think in the right direction to arrive at the solution.
function h(N) {
if (N==1) return 3;
else {
sum = 1;
i = 0;
while (i < h(N-1))
sum = sum + i;
i = i + 1;
return sum;
}
}
According to me, since h(N-1) is called repeatedly in the while loop, the while loop should run as many number of times as what is returned by h(N-1). Besides that, the function call h(N-1) in the while loop will also happen that many number of times. Thus, according to me, I should get something like this:
T(N) = T(N-1)*H(N-1) + C*H(N-1) + D
where
1. T(N) is the running time,
2. T(N-1)*H(N-1) because the one recursive call to h(N-1) will take T(N-1) and since it's recomputed every time the comparison is made, it will be called H(N-1) times. (where H(N-1) is the value returned from the call)
3. and C*H(N-1) is the running time for the statements inside the while loop (since the while loop runs H(N-1) times.
I did not get a satisfactory answer from my professor and I would appreciate if someone could help me understand this.
Thank you!
