How to allow more memory and avoid stack overflow on lots of recursion?

前端 未结 5 2048
-上瘾入骨i
-上瘾入骨i 2021-01-06 19:33

I\'m testing the timing of an algorithm that does lots of recursive calls. My program dies at about 128k recursive calls, and this takes only .05 seconds. I\'d like to allow

5条回答
  •  梦谈多话
    2021-01-06 19:57

    Try to organize your recursive function to have tail recursion.

    That is to say, make sure the last operation of your recursive function is the recursive call. By doing this, the compiler can optimize it into simply iterations.

    Tail recursion will help you because iterations will dramatically decrease the stack space used.

    With tail recursion, you typically pass your value UP all the way, calculating 1 step at a time. So when the recursion is done, all that needs to be done is to return.


    Example:

    Convert the following code:

    unsigned fact(unsigned x)
    {
      if(x == 1)
        return 1;
    
       //--> Not tail recursive, multiply operation after the recursive call
       return fact(x-1) * x;
    }
    

    To this:

    unsigned fact(unsigned x)
    {
        return tail_fact(x, 1);
    }
    
    unsigned tail_fact(unsigned x, unsigned cur_val)
    {
      if(x == 1)
        return cur_val;  
    
      return tail_fact(x-1, x * cur_val);  
    }
    

提交回复
热议问题