From Recursive To Iterative Function

Hello ,
I am trying to make from f_rec (recursive function) to f_iter (iterative function) but I can't.
(My logic was to create a loop to calculate the results of f_rec(n-1), another loop for 2*f_rec(n-2) and one loop for f_rec(n-3);
But I'm wrong)

1
2
3
4
5
6
7
8
9
10
11
int f_rec(int n)
{
 if(n>=3)
   return f_rec(n-1)+2*f_rec(n-2)+f_rec(n-3);
 else 
   return 1;
}

int f_iter(int n)
{
}


I also think that my run time for the f_rec is 3^n , please correct me if I'm wrong.

Thank you
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using std::cout;
using std::endl;
#include <cstdlib>

int f_rec(int n)
{
    if (n >= 3)
        return f_rec(n - 1) + 2 * f_rec(n - 2) + f_rec(n - 3);
    else 
        return 1;
}

int f_iter(int n)
{
    int res[n + 1];

    for (unsigned int i = 0; i < 3; i++)
        res[i] = 1;

    for (unsigned int i = 3; i <= n; i++)
        res[i] = res[i - 1] + 2 * res[i - 2] + res[i - 3];

    return res[n];

} /* f_iter() */

int main(int argc, char *argv[])
{
    for (int n = 1; n < 11; n++)
    {
        cout << "f_rec(" << n << ") = " << f_rec(n) << endl;
        cout << "f_iter(" << n << ") = " << f_iter(n) << endl;
        cout << endl;
    }

    return EXIT_SUCCESS;
}
thanks
Topic archived. No new replies allowed.