Question

Q5 (25pts) Consider the code: int foo(int N){ if (N <= 3) return 2; int res1 = 3*foo(N-4); int...

Q5 (25pts) Consider the code:
int foo(int N){
if (N <= 3) return 2;
int res1 = 3*foo(N-4);
int res2 = foo(N-2);
return res1-res2;
}
a) (6 points) Write the recurrence formula for the time complexity of this function (including the base cases) for N>=0. You do NOT need to solve it.
b) (5 points) Draw the tree that shows the function calls performed in order to compute foo(8) (the root will be foo(8) and it will have a child for each recursive call.)
c) (4pts) In the tree, show the return values for function calls (2pts) and fill in the answer below
foo(8) = _____________________________________________ (2 out of 4 pts)
d) (7pts) Write code for foo_mem, the memoized version of foo (use a solution array to look-up and store results of recursive calls). Comment [O6]: NOT posted
5
e) (3pts) Write the wrapper function that calls the foo_mem function.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

a)

b)

c)

foo(8) = 3*foo(4) - foo(6)

foo(6) = 3*foo(2) - foo(4)

foo(4) = 3*foo(0) - foo(2) = 3*2 - 2 = 4

foo(6) = 3*2 - 4 = 2

  foo(8) = 3*4 - 2 = 10

foo(8) = 10

d)

int foo_mem(int N) {

    int arr[N+1];

    arr[0] = arr[1] = arr[2] = arr[3] = 2;

    for (int i = 4; i <= N; i++)

        arr[i] = 3*arr[i-4] - arr[i-2];

    return arr[N];

}

e)

#include<iostream>

using namespace std;

int foo_mem(int N) {

    int arr[N+1];

    arr[0] = arr[1] = arr[2] = arr[3] = 2;

    for (int i = 4; i <= N; i++)

        arr[i] = 3*arr[i-4] - arr[i-2];

    return arr[N];

}

int main() {

    cout << foo_mem(8);

    return 0;

}

Add a comment
Know the answer?
Add Answer to:
Q5 (25pts) Consider the code: int foo(int N){ if (N <= 3) return 2; int res1 = 3*foo(N-4); int...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT