Increase recursion depth?

Pages: 12
He means you could essentially emulate the recursion yourself, take this example:
task t(num)
{
    std::stack tasks;
    tasks.push(num)
    while(tasks is not empty)
    {
        perform operations with tasks.top()
        instead of recursion, push another number onto tasks
        to 'return' a value, pop the top of tasks and store the return somewhere
    }
}
Last edited on
I have absolutely no idea how to do that O.o

How would I set something like that up with a function that has so many recursive calls?
The only way to handle this without changing your algorithm is to use system-specific calls to increase your stack space. I reccommend the former.
Last edited on
I don't see how to change it without using for loops, though, and I don't understand this stack business. How does it work in a program with multiple calls?
The function would no longer be truly recursive, and therefor would no have multiple calls. std::stack would be used to emulate the effect of recursion without as much overhead and wouldn't require any nested for loops.
Check this out:

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <map>

using namespace std;

int max_depth;

int recursive_function(int n, int depth = 0)
{
    if (depth > max_depth) max_depth = depth;

    if (n <= 0) return 0;

    return recursive_function(n - 1, depth + 1)
         + recursive_function(n - 2, depth + 1);
}

int recursive_function_with_cache(int n, int depth = 0)
{
    static map<int, int> cache;

    if (depth > max_depth) max_depth = depth;

    if (n <= 0) return 0;

    int ret = 0;

    map<int, int>::iterator it = cache.find(n);

    if (it != cache.end()) return it->second;

    ret = recursive_function_with_cache(n - 1, depth + 1)
        + recursive_function_with_cache(n - 2, depth + 1);

    cache[n] = ret;

    return ret;
}

int main()
{
    cout << "evaluating function for n = 30..." << endl;

    max_depth = 0; recursive_function(30);
    cout << "max depth = " << max_depth << endl;

    cout << "evaluating function for n = 30"
        << " in multiple steps..." << endl;

    max_depth = 0; recursive_function_with_cache(10);
    cout << "max depth = " << max_depth << endl;

    max_depth = 0; recursive_function_with_cache(20);
    cout << "max depth = " << max_depth << endl;

    max_depth = 0; recursive_function_with_cache(30);
    cout << "max depth = " << max_depth << endl;

    return 0;
}
Last edited on
Topic archived. No new replies allowed.
Pages: 12