Hey everyone,
I'm working on an algorithm class now, and I'm trying to understand recursion better. I have a problem that that requires writing a recursive function for a problem using dynamic programming. I have come up with a standard non recursive function, to try and understand the problem better in my mind before converting this to recursion with dynamic programming. However I would like to know if my function is correct for this problem.
Pn = Pn-1 + 2Pn-2, P1 = P0 = 1
int P(int n)
{
int value = 0;
for (int a = n; a >= 2; --a)
{ value += (a - 1); }
for (int b = n; b >= 2; b = b - 2)
{ value += 2 * (b - 2); }
value += 2; // for P1 = P0 = 1
return value;
}
Am I correct on this? Thanks for any and all help!
Firekhan
I'm working on an algorithm class now, and I'm trying to understand recursion better. I have a problem that that requires writing a recursive function for a problem using dynamic programming. I have come up with a standard non recursive function, to try and understand the problem better in my mind before converting this to recursion with dynamic programming. However I would like to know if my function is correct for this problem.
Pn = Pn-1 + 2Pn-2, P1 = P0 = 1
int P(int n)
{
int value = 0;
for (int a = n; a >= 2; --a)
{ value += (a - 1); }
for (int b = n; b >= 2; b = b - 2)
{ value += 2 * (b - 2); }
value += 2; // for P1 = P0 = 1
return value;
}
Am I correct on this? Thanks for any and all help!
Firekhan