Are there any example of Mutual recursion?

前端 未结 8 786
迷失自我
迷失自我 2021-02-04 09:48

Are there any examples for a recursive function that calls an other function which calls the first one too ?

Example :

function1()
{    
    //do something         


        
8条回答
  •  不知归路
    2021-02-04 10:10

    It's a bit contrived and not very efficient, but you could do this with a function to calculate Fibbonacci numbers as in:

    
    fib2(n) { return fib(n-2); }
    
    fib1(n) { return fib(n-1); }
    
    fib(n)
    {
      if (n>1)
        return fib1(n) + fib2(n);
      else
        return 1;
    }
    

    In this case its efficiency can be dramatically enhanced if the language supports memoization

提交回复
热议问题