简体   繁体   中英

Understanding recurrence relations with function calls inside loops

int fun (int n)
{
  int x=1, k;
  if (n==1) return x;
  for (k=1; k<n; ++k)
     x = x + fun(k) * fun(n – k);
  return x;
}

The recurrence relation in the solution is given as :

在此处输入图片说明

Solving this is easy, I got the answer to be 51.

The doubt is why the '1' (underlined in red) is outside the summation?

I understand if it were asymptotic analysis, we would consider it constant time because we only need to know the nature of growth, but since here we need an accurate answer.

Since this line x + fun(k) * fun(n – k) in inside the loop, x also loops, so why is it outside summation?

Most running sums begin at 0. However, this one begins at 1. That constant value is the one you underlined. It comes from the line

int x=1 , k;

For each 'k' in for loop, x is getting replaced for the previous iteration value of x. Thus there wont be addition of the variable x but simply substitution.

consider f(3),

for k =1, x=x+f(1)*f(2)....1

again loop runs, k=2

x=x+f(2)*f(1)....2

substituting x from 1,

x=x+f(2)*f(1)+f(1)*f(2).

Carry out the same for everything.. and substitute x= 1 at end.. u will get the GENERALIZED EQUATION YOU HAVE GIVEN.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM