Fibonacci sequence - recursive

Recursive implementation of the Fibonacci sequence

  • First to define a fibonacci series:
    Fibonacci series refers to such a series: 1,1,2,3,5,8,13,21,34, ...... In mathematics, Fibonacci columns to be as follows the method defined recursion: F. (. 1) =. 1, F. (2) =. 1, F. (n-) = F. (n--. 1) + F. (n-- 2) (n-≥. 3, n-∈ N *.
    the Fibonacci series achieved in the program is very easy, he is a typical recursive algorithm can be realistic.
  • Let's take a recursive common wording:
int fibo(int n)
{
        if(n == 1 || n == 2)
                return 1;
        return fibo(n-1)+fibo(n-2);

}
int main()
{
        int n,result;
        printf("请输入:");
        scanf("%d",&n);
        result = fibo(n);
        printf("%d\n",result);
}

Recursive code is simple, but if you do not do some optimization, it is prone to stack overflow. Or more memory-intensive will be achieved, because when n> 2, fibo function calls itself needs to n-2 times began to return a value, then one by one return to their original open and start to function. If the value of n required is very large, it may need to save hundreds or thousands of call records, it is prone to "stack overflow" error (stack overflow).

  • But we can do a little more optimized implementation - tail recursion
    tail recursion means that, when the function returns, calls itself itself, and, return statement can not contain expressions. In this way, the compiler or interpreter you can do to optimize tail recursion, the recursive call to itself, no matter how many times, only occupy a stack frame, stack overflow situation does not occur.
    In general, since there is only one call record, it will never be "stack overflow" error occurred.
    The optimized recursive function:
int fibo(int n,int i,int j)
{
        if(n ==1 || n ==2)
                return j;
        return fibo(n-1,j,j+i);
}

int main()
{
        int n,result;
        printf("请输入:");
        scanf("%d",&n);
        result = fibo(n,1,1);
        printf("%d\n",result);
}

As a result, when fibo function calls itself, we began to have return value, not at the end of a recursive one by one and then return to the original function return values. Tail-recursive implementation, the compiler can help us save a lot of memory consumption, my mother no longer have to stack overflow!

Guess you like

Origin www.cnblogs.com/tansss/p/12507644.html